Home > Back-end >  unable to read data from a text file in c
unable to read data from a text file in c

Time:04-23

//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

CodePudding user response:

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);
  •  Tags:  
  • c
  • Related