Saturday, August 27, 2011

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");
scanf("%s%d%f",e.name,&e.age,&e.bs);
fwrite(&e,sizeof(e),1,fp);
fclose(fp);
}

Reading from the binary file


The following code segment illustrates how to read data from file in binary format.

fp = fopen("EMP.DAT","rb");
while(fread(&e,sizeof(e),1,fp)==1){
   printf("%s %d %f\n",e.name,e.age,e.bs);
}
fclose(fp);

1 comment:

  1. how to use with array of structure brother kindly answer me

    ReplyDelete