How to read particular data from file using fread?

给你一囗甜甜゛ 提交于 2019-12-25 12:23:33

问题


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?


回答1:


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



回答2:


Doing fread operations of sizeof(student.marks) number of bytes at a time may give you spurious results, given how you did fwrite operations on sizeof(student) numbers of bytes.

Another way to think about this is to pretend you're a book publisher. You print or write a book onto one piece of paper at a time. When you want to go back and find the page number on each page, you wouldn't read the pages one word at a time. That will give you a weird/wrong answer. You read in the whole page to get back the page number you want.

Investigate fread-ing sizeof(student) number of bytes on each iteration, writing those bytes into a student struct. Then access the marks property of that struct.



来源:https://stackoverflow.com/questions/43329937/how-to-read-particular-data-from-file-using-fread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!