如何使用fread从文件中读取特定数据? [英] How to read particular data from file using fread?

查看:775
本文介绍了如何使用fread从文件中读取特定数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);


}

如您在输出图像中所见,还将打印具有其他一些值的标记,而对于所需的输出标记,仅需要具有值91和94即可.

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?

推荐答案

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

You are reading and writing records of different lengths, and thus your reads are giving you empty floating point numbers. If you write your records as three segments of a structure, you must read back the entire length of the structure to locate the fields you are interested in.

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

这篇关于如何使用fread从文件中读取特定数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆