In the above cases we found that storing number in the format provided by the formatted Input/Output functions take up a lot of disk space, because each digit is stored as a character. Similarly formatted Input/Output has another problem: there is not direct way top read and write complex data types such as arrays and structures. Arrays can be handled inefficiently by writing each array element one at a time.
A possible solution for this problem is record input/output which is sometimes called “block input/output”. Record I/O writes number to disk file in binary (untranslated) format, so that integers are stored in 4 bytes, and so on for the other numerical types. Record I/O also permits writing any amount of data at once. Array, structure, and other data construction can be written with a single statement. The functions used for this purpose are fread() and fwrite().
fread() and fwrite()
To read and write data types that are longer than one byte, the C file system provides two functions: fread() and fwrite(). These functions allow the reading and writing of blocks of any type of data (they are used for reading and writing records with binary file).the following program writes and reads data to and from binary file.
Syntax of the functions fread( ) and fwrite( ):
where n is number of time to be read or write
Program to write and read the data of structure to and from data file
struct employee e;
printf(“ cannot open file”);
printf(“Enter name, age, and basic salary:\n”);
printf(“Add another record(y\n)”);
while(choice= =”y”|| choice = =”y”);
rewind(fp); //Moves file pointer to the beginning to read from the beginning
The information obtained about the employee from the keyboard is placed in the structure variable e. Then, the following statement writes the structure to the file.
Here the first argument is the address of the structure to be written to the disk. The second argument is the size of the structure bytes. Instead of counting the bytes occupied by the structure ourselves, we let the program do it for us by using sizeof() operator ,which gives the size of the variables in bytes. The third argument is the number of such structures that we want to write at one time. The last argument is the pointer to the file that we want to write to.
The fread() function causes the data read from the disk to be placed in the structure variable e. the format of fread() is same as fwrite(). The function fread() reads the numbers of records read. If we have reached the end of file, since fread() cannot read anything, it returns 0.
Program on reading and writing arrays with records I/O function
printf(“cannot open the file”);
printf(“Data has been written on file successfully……\n”);