Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading