Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Writing and Reading a Binary File Create a text file that stores a First name, a

ID: 3927541 • Letter: W

Question

Writing and Reading a Binary File

Create a text file that stores a First name, a last name, and an age, one record per line.

The C program will read a line of text from this file and then create a structure (what other languages would call a record) containing that data. Then write the object in a new binary file. The binary file that you have created should contain a series of records, each record containing a first name, last name and an age.

The program should then close the file and re-open it for input, read the file record by record and display on the screen, one record per line.

Explanation / Answer

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 ",e.name,e.age,e.bs);

}

fclose(fp);