简体   繁体   中英

unable to read data from a text file in c

//here's the structure typedef struct student { int rno; char name[20]; struct subject { int scode; char sname[20]; int mark; } sub[3]; int total; float per; } student;

student s1;
    FILE *fp;
    int j;
    fp = fopen("mystudents.txt", "r");

    while (fread(&s1, sizeof(student), 1, fp))
    {
        printf("\n%d \n%s", s1.rno, s1.name);
        for (j = 0; j < 3; j++)
        {
            printf("\n%d", s1.sub[j].mark);
        }
        printf("\n%d", s1.total);
    }
    fclose(fp);

Content of my file:

101 brian 23 45 56 124
102 abhi 32 78 90 200

fread() is for reading binary files, not text files (unless you're reading into a string variable). You can use fscanf() to parse the text file.

student s1;
FILE *fp;
fp = fopen("mystudents.txt", "r");

while (fscanf(fp, "%d %s %d %d %d %d", &s1.rno, s1.name, &s1.sub[0].mark, &s1.sub[1].mark, &s1.sub[2].mark, &s1.total) > 0)
{
    printf("\n%d \n%s", s1.rno, s1.name);
    for (int j = 0; j < 3; j++)
    {
        printf("\n%d", s1.sub[j].mark);
    }
    printf("\n%d", s1.total);
}
fclose(fp);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM