【问题标题】:How to read particular data from file using fread?如何使用 fread 从文件中读取特定数据?
【发布时间】:2017-04-10 18:01:34
【问题描述】:

以下代码使用 fwrite 将 student 的数据写入文件并使用 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 的标记

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

【问题讨论】:

  • 你需要回读整个结构。
  • fread(&amp;student.marks,sizeof(student.marks),1,fp) --> fread(&amp;student,sizeof(student),1,fp)

标签: c file-handling fwrite fread


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    另一种思考方式是假设您是图书出版商。您一次在一张纸上打印或写一本书。当您想返回并查找每一页上的页码时,您不会一次读一个字。这会给你一个奇怪/错误的答案。您阅读整页以获取所需的页码。

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

    【讨论】:

      猜你喜欢
      • 2014-03-14
      • 2019-10-13
      • 2020-06-09
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      相关资源
      最近更新 更多