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,