Following code writes data of student into a file using fwrite and reads data using fread:
struct record
{
char name[20];
int roll;
float marks;
}student;
#include<stdio.h>
void main()
{
int i;
FILE *fp;
fp=fopen("1.txt","wb"); //opening file in wb to write into file
if(fp==NULL) //check if can be open
{
printf("\nERROR IN OPENING FILE");
exit(1);
}
for(i=0;i<2;i++)
{
printf("ENTER NAME, ROLL_ NO AND MARKS OF STUDENT\n");
scanf("%s %d %f",student.name,&student.roll,&student.marks);
fwrite(&student,sizeof(student),1,fp); //writing into file
}
fclose(fp);
fp=fopen("1.txt","rb"); //opening file in rb mode to read particular data
if(fp==NULL) //check if file can be open
{
printf("\nERROR IN OPENING FILE");
exit(1);
}
while(fread(&student.marks,sizeof(student.marks),1,fp)==1) //using return value of fread to repeat loop
printf("\nMARKS: %f",student.marks);
fclose(fp);
}
As you can see in output image, marks with some other values are also printed whereas for desired output marks only with with value 91 and 94 are required
Which corrections are needed to be done in the above code to get desired output?