Tuesday, 12 February 2013

Writing into and reading from a binary file in C

In previous example, you learn how to write and read a text file in C. If the number of fields in the structure increase, writing structures using fprintf(), or reading them using fscanf(), becomes quite clumsy. The more efficient way of writing records(structures) can be achieved by the use of two functions fread() and fwrite(). The fwrite() functions writes whole structures at a time and fread() function read all the fields at a time.
Writing into the binary file
The following code segment illustrates how to write data into file in binary format.

struct emp{
   char name[20];
   int age;
   float bs;
struct emp e;
fp = fopen("EMP.DAT","wb");
if(fp == NULL){
   puts("Cannot open file");
printf("Enter name, age and basic salary");

No comments:

Post a Comment