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

How to read particular data from file using fread?

以下代码使用 fwrite 将学生的数据写入文件并使用 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);


}

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

需要在上述代码中进行哪些更正才能获得所需的输出?

一次对 sizeof(student.marks) 个字节数进行 fread 操作可能会产生虚假结果,考虑到您对 sizeof(student) 个字节数进行 fwrite 操作的方式。

另一种思考方式是假设您是图书出版商。您一次在一张纸上打印或写一本书。当您想返回并在每一页上查找页码时,您不会一次一个单词地阅读这些页面。这会给你一个 weird/wrong 的答案。您阅读整页以取回您想要的页码。

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

您正在读取和写入不同长度的记录,因此您读取的是空浮点数。如果将记录写成一个结构的三段,则必须读回结构的整个长度以定位您感兴趣的字段。

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