如何使用fread从文件中读取特定数据?

以下代码使用fwrite将student的数据写入文件并使用fread读取数据:

struct record { char name[20]; int roll; float marks; }student; #include 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); } 

**上述计划的输出**

正如您在输出图像中看到的那样,还会打印带有其他值的标记,而对于所需的输出标记,仅需要值为91和94的标记

在上面的代码中需要进行哪些修正以获得所需的输出?

您正在读取和写入不同长度的记录,因此您的读取将为您提供空的浮点数。 如果将记录编写为结构的三个段,则必须回读结构的整个长度以找到您感兴趣的字段。

 while(fread(&student, sizeof(student), 1, fp) == 1)) //using return value of fread to repeat loop printf("\nMARKS: %f",student.marks); 

考虑到如何对sizeof(student)字节数进行fwrite操作,一次执行sizeof(student.marks)字节数的fread操作可能会给出虚假结果。

考虑这个问题的另一种方法是假装你是图书出版商。 您可以一次在一张纸上打印或书写一本书。 当您想要返回并在每个页面上找到页码时,您不会一次读取一个单词的页面。 这会给你一个奇怪/错误的答案。 您在整个页面中阅读以获取所需的页码。

调查每次迭代的fread -ing sizeof(student)字节数,将这些字节写入student结构中。 然后访问该结构的marks属性。