Programmer-Defined Data Types 269
Perso n_print ( p3 );46
Pers on_des truct ( p1 );47
Pers on_des truct ( p2 );48
Pers on_des truct ( p3 );49
return EXIT _SUCCES S ;50
}51
Person * P e rson_ const r uct ( char * n , i nt y , i n t m , i n t d )52
{53
Person * p ;54
p = malloc ( s i z e o f ( Person ) );55
i f (p == NULL )56
{57
printf (" malloc fail n ");58
return NULL ;59
}60
p -> name = malloc ( s i z e o f ( char) * ( strlen ( n) + 1) );61
// + 1 for the ending characte r 0 62
strcpy (p -> name , n) ;63
p -> dob = Dat eOfBi rth_ const ruct (y , m , d );64
return p ;65
}66
void Pers o n_des truct ( Person * p )67
{68
// p must be re l e ased after p -> name has been released69
free ( p -> name ) ;70
free ( p);71
}72
Person * Per son_copy ( Person * p )73
{74
return Per son_c onstru ct ( p -> name , p -> dob . year ,75
p -> dob . month , p -> dob . date ) ;76
}77
Person * Pe rson_as sign ( Person * p1 , Person * p2 )78
{79
free ( p1 -> name );80
81
p1 -> dob = p2 -> dob ;82
p1 -> name = strdup ( p2 -> name );83
84
return p1;85
}86
void Person _print ( Person * p )87
{88
printf (" Name : %s. " , p -> name );89
Date OfBir th_pr int ( p -> dob ) ;90
}91
This program creates a hierarchy of structures. Then, Person construct calls
DateOfBirth construct. Person print calls DateOfBirth print. What is the advantage
of this approach? As programs become more complex, such a hierarchy becomes helpful
for organization. Creating one structure that contains everything can be impractical and
270 Intermediate C Programming
unclear. Instead, we should put related data together and create a structure, for example,
the DateOfBirth structure. We can use this structure inside other structures.
Each structure should have a constructor to initialize all attributes. If a structure has
pointers for dynamically allocated memory, then make sure that there is also a destructor.
If deep copy is required (true in most cases), remember to write a copy constructor and an
assignment function.
16.6 Binary Files and Objects
This section explains how to write an object to a file and how to read an object from a file.
This section will talk about both text files and binary files. Vector is used as the structure
for the examples in this section. The following program contains two write functions and
two read functions. Vector writet and Vector readt use text files. Vector writeb and
Vector readb use binary files.
When using text files, reading and writing objects is as simple as reading and writing one
attribute after another. The two functions must process the attributes in the same order. If
the orders are different, then the results will be wrong.
Vector writeb and Vector readb open files in the binary mode by adding b in the
second argument when calling fopen. Some operating systems, including Linux, actually
ignore b. It is used primarily for compatibility among different systems. Table 16.1 describes
the differences of text and binary files:
Operation Text File Binary File
open a file fopen fopen
write fprintf fwrite
read fgetc, fgets, or fscanf fread
TABLE 16.1: Functions for opening, writing to, and reading from text and binary files.
// vec torfile .c1
#in clude < stdio .h >2
#in clude < stdlib .h >3
#in clude < string .h >4
#in clude " vector .h "5
Vector Ve ctor_ constr uct ( i n t a , i n t b , in t c)6
{7
Vector v;8
v. x = a;9
v. y = b;10
v. z = c;11
return v ;12
}13
void Vector _print ( char * name , Vector v )14
{15
printf (" %s is (% d , %d , %d) .n " , name , v.x , v.y , v .z );16
}17
void Vecto r_write t ( char * filename , Vector v )18
Programmer-Defined Data Types 271
// writet means write to a text file19
{20
FILE * fptr ;21
fptr = fopen ( filename , " w") ;22
i f ( fptr == NULL )23
{24
printf (" Vec tor_wri tet fopen fail n ");25
return ;26
}27
fprintf ( fptr , " %d %d %d ", v .x , v.y , v. z);28
fclose ( fptr );29
}30
Vector Vec tor_rea d t ( char * f ilename )31
// readt means read from a text file32
{33
Vector v = Vec tor_c o nstru ct (0 , 0 , 0) ;34
FILE * fptr ;35
fptr = fopen ( filename , " r") ;36
i f ( fptr == NULL )37
{38
printf (" Vec t or_read t fopen fail n ");39
return v ;40
}41
i f ( fscanf ( fptr , " %d %d %d ", & v .x, & v .y , & v. z) != 3)42
{43
printf (" fprintf fail n ");44
}45
fclose ( fptr );46
return v ;47
}48
void Vecto r_write b ( char * filename , Vector v )49
// writeb means write to a binary file50
{51
FILE * fptr ;52
fptr = fopen ( filename , " w") ; // "w " same as " wb " in Linux53
i f ( fptr == NULL )54
{55
printf (" Vec tor_wri teb fopen fail n ");56
return ;57
}58
i f ( fwrite (& v , s i z e o f ( Vector ) , 1, fptr ) != 1)59
{60
printf (" fwrite fail n ");61
}62
fclose ( fptr );63
}64
Vector Vec tor_rea d b ( char * f ilename )65
// readb means read from a binary file66
{67
FILE * fptr ;68
Vector v; // not i n itialize d69
272 Intermediate C Programming
fptr = fopen ( filename , " r") ; // "r " same as " rb " in Linux70
i f ( fptr == NULL )71
{72
printf (" Vec t or_read b fopen fail n ");73
return v ;74
}75
i f ( fread (& v , s i z e o f ( Vector ) , 1, fptr ) != 1)76
{77
printf (" fread fail n ");78
}79
return v ;80
}81
int main ( i n t argc , char * argv [])82
{83
Vector v1 = Vecto r_con struct (13 , 206 , -549) ;84
Vector v2 = Vecto r_con struct (-15 , 8762 , 1897) ;85
Vecto r_print (" v1 " , v1) ;86
Vecto r_print (" v2 " , v2) ;87
printf (" == === = === ==== ==== ==== === = === = == n ");88
Vecto r_write t ( " vectort . dat " , v1 );89
v2 = V e ctor_re adt ( " vectort . dat ") ;90
Vecto r_print (" v1 " , v1) ;91
Vecto r_print (" v2 " , v2) ;92
93
v1 = V ector _ const ruct (2089 , -3357 , 1234) ;94
v2 = V ector _ const ruct (7658 , 0, 1876) ;95
printf (" == === = === ==== ==== ==== === = === = == n ");96
Vecto r_print (" v1 " , v1) ;97
Vecto r_print (" v2 " , v2) ;98
99
Vecto r_write b ( " vectorb . dat " , v1 );100
v2 = V e ctor_re adb ( " vectorb . dat ") ;101
printf (" == === = === ==== ==== ==== === = === = == n ");102
Vecto r_print (" v1 " , v1) ;103
Vecto r_print (" v2 " , v2) ;104
return EXIT _SUCCES S ;105
}106
To write binary data, fwrite is used. This function requires four arguments:
1. The address of the object. If it is an object (not a pointer), & needs to be added before
the object.
2. The size of the object. It can be obtained by using sizeof to find the size of the
object or data. For this example, the size of a Vector object is sizeof(Vector).
3. The number of objects to write. This example writes only one object so the value
is 1. If a program is writing an array of objects, then this argument is the number of
elements in the array.
4. The FILE pointer.
The return value of fwrite is the number of objects written. This number can be
different from the third argument because, for example, the disk may be full and only some
elements are written. It is a good programming habit to check whether the return value is
the same as the third argument. The data written by fwrite needs to be read by fread,
Programmer-Defined Data Types 273
not fscanf. Four arguments are required for fread and the order of the arguments is the
same as that for fwrite.
What are advantages and disadvantages of text and binary files? If data are stored in a
text file, then it can be read by using the more command in terminal or simply viewing it
in your favorite text editor. Vector readt and Vector writet must handle the attributes
one by one. The order in Vector writet must be the same as the order in Vector readt. If
one more attribute is added to Vector (for example, t for time), then both Vector readt
and Vector writet must be changed. These requirements increase the chances of mistakes:
It is easy to change one place and forget to change the other. In contrast, Vector writeb
and Vector readb automatically handle the order of attributes. If an attribute is added
to Vector, there is no need to change Vector readb and Vector writeb because sizeof
reflects the new size. The disadvantage of using binary files is that they cannot be edited
and viewed directly. The data files are also specific to the platform the code is compiled on,
since the size and format of the binary data can vary between computers.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset