Computer Programming
[ECEg-1052]
Chapter Seven:
Structure and Files
2018 E.C
Outline
Defining the structure
Pointers to structures
Nesting structures
User defined data types
Introduction to files
Defining the structure
A data structure is a set of diverse types of data that may have different
lengths grouped together under a unique declaration.
Its form is the following:
struct model_name {
type1 element1;
type2 element2;
type3 element3;
. .
} object_name;
3
Cont’d...
where
model_name is a name for the model of the structure type and the optional
parameter object_name is a valid identifier (or identifiers) for structure
object instantiations.
Within curly brackets { } they are the types and their sub-identifiers
corresponding to the elements that compose the structure.
4
Cont’d...
For example: Once declared, products has become a
new valid type name like the fundamental
struct products { ones int, char or short and we are able to
declare objects (variables) of that type.
char name [30];
float price;
};
products apple;
products orange, melon;
5
Cont’d...
The optional field object_name that can go at the end of the structure
declaration serves to directly declare objects of the structure type.
For example we can also declare the structure objects apple, orange and
melon this way:
struct products {
char name [30];
float price;
} apple, orange, melon;
6
Cont’d...
Once we have declared our three objects of a determined structure model
(apple, orange and melon) we can operate with the fields that form them.
To do that we have to use a point (.) inserted between the object name and
the field name.
For example, we could operate with any of these elements as if they were
standard variables of their respective types:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
7
Cont’d...
Each one being of its corresponding data type:
• [Link], [Link] and [Link] are of type char[30], and
• [Link], [Link] and [Link] are of type float.
Moreover, in cases like the last one in which we took advantage of the
declaration of the structure model to declare objects of it, the parameter
model_name (in this case products) becomes optional.
Although if model_name is not included it will not be possible to declare
more objects of this same model later.
8
Cont’d...
It is important to clearly differentiate between what is a structure model,
and what is a structure object.
Using the terms we used with variables, the model is the type, and the
object is the variable.
We can instantiate many objects (variables) from a single model (type).
9
Cont’d...
Example
// introduces operator new
#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;
struct movies_t {
char title [50];
int year;
} mine, yours;
void printmovie (movies_t movie);
int main (){
char buffer [50];
strcpy ([Link], "2001 A Space Odyssey");
[Link] = 1968;
10
Cont’d...
cout << "Enter title:\n "; Output:
[Link] ([Link], 50); Enter title: Alien
cout << "Enter year:\n "; Enter year: 1979
My favourite movie is: 2001 A
[Link] (buffer,50); Space Odyssey (1968)
[Link] = atoi (buffer); And yours: Alien (1979)
cout << "My favourite movie is: "<<printmovie (mine);
cout << "And yours:\n "<<printmovie (yours);
}
void printmovie (movies_t movie){
cout << [Link]<< "\n ";
cout << " (" << [Link] << ")\n";
} 11
Cont’d...
Example 2
// array of structures
#include<iostream.h>
#include <stdlib.h>
#define N_MOVIES 5
struct movies_t {
char title [50];
int year;
} films [N_MOVIES];
void printmovie (movies_t movie);
int main (){
char buffer [50];
int n;
12
Cont’d...
for (n=0; n<N_MOVIES; n++) { Output:
cout << "Enter title: "; Enter title: Alien
[Link] (films[n].title,50); Enter year: 1979
cout << "Enter year: "; Enter title: Blade Runner
[Link] (buffer,50); Enter year: 1982
Enter title: Matrix
films[n].year = atoi (buffer); Enter year: 1999
} Enter title: Rear Window
cout << "\nYou have entered these movies:\n"; Enter year: 1954
for (n=0; n<N_MOVIES; n++) Enter title: Taxi Driver
printmovie (films[n]); Enter year: 1975
return 0; You have entered these movies:
Alien (1979)
}
Blade Runner (1982)
void printmovie (movies_t movie){
Matrix (1999)
cout << [Link]; Rear Window (1954)
cout << " (" << [Link] << ")\n"; Taxi Driver (1975)
} 13
Pointers to structures
The rules are the same as for any fundamental data type.
The pointer must be declared as a pointer to the structure:
struct movies_t {
char title [50];
int year;
};
movies_t amovie;
movies_t * pmovie;
Here amovie is an object of struct type movies_t and pmovie is a pointer to
point to objects of struct type movies_t.
So, the following, 14
Cont’d...
Example: Output:
// pointers to structures
#include <iostream.h> Enter title: Matrix
#include <stdlib.h> Enter year: 1999
struct movies_t {
char title [50];
int year; You have entered:
}; Matrix (1999)
int main (){
char buffer[50];
movies_t amovie;
movies_t * pmovie;
pmovie = & amovie;
cout << "Enter title: ";
[Link] (pmovie->title,50);
cout << "Enter year: ";
[Link] (buffer,50);
pmovie->year = atoi (buffer);
cout << "\nYou have entered:\n";
cout << pmovie->title;
cout << " (" << pmovie->year << ")\n";
} 15
Cont’d...
The operator -> a reference operator that is used exclusively with pointers
to structures and pointers to classes.
It allows us not to have to use parenthesis on each reference to a structure
member.
For example we can write:
pmovie -> title
that could be translated to:
(*pmovie).title
Both expressions pmovie -> title and (*pmovie).title are valid and mean
that we are evaluating the element title of the structure pointed by pmovie.
16
Cont’d...
You must distinguish it clearly from:
*[Link]
that is equivalent to
*([Link])
and that would serve to evaluate the value pointed by element title of
structure movies, that in this case (where title is not a pointer) it would not
make much sense.
17
Cont’d...
Expression Description Equivalent
[Link] Element title of structure pmovie
Element title of structure pointed by
pmovie->title pmovie (*pmovie).title
Value pointed by element title of
*[Link] structure pmovie *([Link])
18
Nesting structures
Structures can also be nested so that a valid element of a structure can also
be another structure.
struct movies_t {
char title [50];
int year;
}
struct friends_t {
char name [50];
char email [50];
movies_t favourite_movie;
} charlie, maria;
19
Cont’d…
friends_t * pfriends = &charlie;
Therefore, after the previous declaration we could use the following
expressions:
[Link]
maria.favourite_movie.title
charlie.favourite_movie.year
pfriends->favourite_movie.year
where, by the way, the last two expressions are equivalent.
20
User defined data types
We have already seen a data type that is defined by the user (programmer):
the structures.
But in addition to these there are other kinds of user defined data types:
•
Definition of own types (typedef)
•
Unions
•
Enumerations (enum)
21
Definition of own types (typedef)
C++ allows us to define our own types based on other existing data types.
In order to do that we shall use keyword typedef, whose form is:
typedef existing_type new_type_name ;
where
existing_type is a C++ fundamental or any other defined type and
new_type_name is the name that the new type we are going to define will
receive.
typedef can be useful to define a type that is repeatedly used within a
program and it is possible that we will need to change it in a later version,
or if a type you want to use has too long a name and want it to be shorter.
22
Cont’d...
For example:
typedef char C;
typedef unsigned int WORD;
typedef char * string_t;
typedef char field [50];
In this case we have defined four new data types:
23
Cont’d...
C, WORD, string_t and field as char, unsigned int, char* and char[50]
respectively, that we could perfectly use later as valid types:
C achar, anotherchar, *ptchar1;
WORD myword;
string_t ptchar2;
field name;
24
Unions
Unions allow a portion of memory to be accessed as different data types,
since all of them are in fact the same location in memory.
Its declaration and use is similar to the one of structures but its functionality
is totally different:
union model_name {
type1 element1;
type2 element2;
type3 element3;
. .
} object_name;
25
Cont’d...
All the elements of the union declaration occupy the same space of
memory.
Its size is the one of the greatest element of the declaration.
For example:
defines three elements:
union mytypes_t {
mytypes.c
char c;
mytypes.i
int i;
mytypes.f
float f;
each one of a different data type.
} mytypes;
26
Cont’d...
Since all of them are referring to a same location in memory, the modification of one of
the elements will affect the value of all of them.
One of the uses a union may have is to unite an elementary type with an array or
structures of smaller elements.
For example,
union mix_t{
long l;
struct {
short hi;
short lo;
} s;
char c[4];
} mix; 27
Cont’d...
defines three names that allow us to access the same group of 4 bytes:
mix.l, mix.s and mix.c and which we can use according to how we want to
access it, as long, short or char respectively.
28
Anonymous unions
In C++ we have the option that unions be anonymous.
If we include a union in a structure without any object name (the one that
goes after the curly brackets { }) the union will be anonymous and we
will be able to access the elements directly by its name.
For example, look at the difference between these two declarations:
29
Cont’d...
union anonymous union
struct { struct {
char title[50]; char title[50];
char author[50]; char author[50];
union { union {
float dollars; float dollars;
int yens; int yens;
} price; };
} book; } book;
30
Cont’d...
The only difference between the two pieces of code is that in the first one
we gave a name to the union (price) and in the second we did not.
The difference is when accessing members dollars and yens of an object.
In the first case it would be:
[Link]
[Link]
whereas in the second it would be:
[Link]
[Link]
31
Enumerations (enum)
Enumerations serve to create data types to contain something different
that is not limited to either numerical or character constants nor to the
constants true and false.
Its form is the following:
enum model_name {
value1,
value2,
value3,
. .
} object_name;
32
Cont’d...
For example, we could create a new type of variable called color to store
colors with the following declaration:
enum colors_t {
black, blue, green, cyan, red, purple, yellow, white
};
For example, once declared the colors_t enumeration in the following
expressions will be valid:
colors_t mycolor;
mycolor = blue;
if (mycolor == green)
33
Cont’d...
In fact our enumerated data type is compiled as an integer and its possible
values are any type of integer constant specified.
If it is not specified, the integer value equivalent to the first possible value
is 0 and the following ones follow a +1 progression.
Thus, in our data type colors_t that we defined before, black would be
equivalent to 0, blue would be equivalent to 1, green to 2 and so on.
34
Cont’d...
If we explicitly specify an integer value for some of the possible values of
our enumerated type (for example the first one) the following values will be
the increases of this,
for example:
enum months_t {
january=1, february, march, april, may, june, july, august, september,
october, november, december
}y2k;
In this case, variable y2k of the enumerated type months_t can contain any of the
12 possible values that go from january to december and that are equivalent to
values between 1 and 12, not between 0 and 11 since we have made january equal
to 1.
35
Introduction to Files
Opening a file
Reading from and writing to a file
Closing a file
Cont’d...
So far, we have been using the iostream standard library, which
provides cin and cout methods for reading from standard input and writing to
standard output respectively.
In this session we will discuss about how to read and write from a file. This
requires another standard C++ library called fstream, which defines three new
data types.
Sr. No Data Type & Description
1 Ofstream-This data type represents the output file stream and is used to create files and to
write information to files.
2 Ifstream-This data type represents the input file stream and is used to read information from
files.
3 Fstream-This data type represents the file stream generally, and has the capabilities of both
ofstream and ifstream which means it can create files, write information to files, and read
information from files.
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file. 37
Opening a File
A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for writing. And ifstream
object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream,
ifstream, and ofstream objects.
void open(const char *filename,ios::openmodemode);
Here, the first argument specifies the name and location of the file to be opened and the
second argument of the open() member function defines the mode in which the file
should be opened.
Sr. No Mode Flag & Description
1 ios::app Append mode. All output to that file to be appended to the end.
2 ios::ate Open a file for output and move the read/write control to the end of the file.
3 ios::in Open a file for reading.
4 ios::out Open a file for writing.
5 ios::trunc If the file already exists, its contents will be truncated before opening the file. 38
Cont’d...
You can combine two or more of these values by ORing them together. For
example if you want to open a file in write mode and want to truncate it in
case that already exists, following will be the syntax.
ofstream outfile;
[Link]("[Link]", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows
fstream afile;
[Link]("[Link]", ios::out | ios::in );
39
Reading from and writing to a file
Writing to a File
While doing C++ programming, you write information to a file from your
program using the stream insertion operator (<<) just as you use that
operator to output information to the screen. The only difference is that
you use an ofstream or fstream object instead of the cout object.
Reading from a File
You read information from a file into your program using the stream
extraction operator (>>) just as you use that operator to input information
from the keyboard. The only difference is that you use
an ifstream or fstream object instead of the cin object.
40
Closing a File
When a C++ program terminates it automatically flushes all the streams,
release all the allocated memory and close all the opened files. But it is
always a good practice that a programmer should close all the opened files
before program termination.
Following is the standard syntax for close() function, which is a member
of fstream, ifstream, and of stream objects.
void close();
Example: Following is the C++ program which opens a file in reading and
writing mode. After writing information entered by the user to a file named
[Link], the program reads information from the file and outputs it onto the
screen.
41
1. #include <fstream> #include <iostream>
2. using namespace std;
3. int main ()
4. { char data[100]; // open a file in write mode. When the above code is compiled and
5. ofstream outfile; executed, it produces the following
[Link]("[Link]");
sample input and output −
6.
7. cout << "Writing to the file" << endl;
cout << "Enter your name: ";
$./[Link] Writing to the file Enter your
8.
9. [Link](data, 100); // write inputted data into the file.
10. outfile << data << endl; name: Zara Enter your age: 9 Reading
cout << "Enter your age: ";
11.
from the file Zara 9
12. cin >> data;
13. [Link](); // again write inputted data into the file.
14. outfile << data << endl; // close the opened file.
15. [Link](); // open a file in read mode.
16. ifstream infile;
17. [Link]("[Link]");
18. cout << "Reading from the file" << endl;
19. infile >> data; // write the data at the screen.
20. cout << data << endl; // again read the data from the file and display it.
21. infile >> data;
22. cout << data << endl; // close the opened file.
23. [Link]();
24. return 0; }
Thank You !
43