Writing Records onto a File Using Structures
The fwrite() function allows us structure to be written onto a file. The following statement writes the structures transrec onto a file called trans.xls:
fwrite ( &transrec, sizeof( struct salesdata), 1, fp);
Here, &transrec is the address of the data to be written. Thus first parameter is a struct type pointer variable initialised to the address of the structure .
The second parameter is the size of the data to be written, i.e. size of the structure transdata. Note that the size is the not the size of the actual structure.
The sizeof operator can be used to determine the size of any data in C, instead of manually determining the size and using the value. The struct keyword must be specified with sizeof, when determining only the size of a structure.
For example, in some machines, int type data occuppy 2 bytes and in some, 4. Using sizeof , the compiler will determine the size of the data item appropriately.
Thethird parameter of fwrite() is the number of data to be written onto the file. If an array of 6 structures has to be written, then the number of data would be 6.
However, the size parameter would still be the size of one structure.
The last parameter is the pointer to the file trans.xls.
Reading Records from Files
Alternatively, the fread() function allows an entire record to be read. The following statement reads one record of the file trans.xls into the structure transrec.
fread ( ptr, sizeof(struct transdata), 1, fp );
The parameters of this function are identical to that of the fwrite() function. As in the case of fwrite(), fread() can be used to read more than one record also, but the size parameter will always be the size of the size of one structure only.
fread() will return the number of records actually read from the file, if the read is successful, should be equal to the number of records asked for.
So, the following statement,
if (( fread (ptr, sizeof ( struct transdata), 1, fp)) != 1)
can be used to check if the read has been successful.
A read can be unsuccessful in case the end-of -file occurs before the number of records requested, or the file is corrupted and hence cannot be read.
A strange feature of the fread() function is that it does not return any indicator in case of end-of-file . The feof() function, makes up for this file. The following feof() statement may be used after the fread() statement.
if (feof(fp))
:
:
Copyright © 2008 Manikkumar. All rights reserved.