0

I have a problem with the structure of C. I want to write a program which reads data fromgrades.txt , save it to the structured array and print it. So I wrote a code below this. program.c

#include <stdio.h>
#include <string.h>

int main()
{
    FILE *fp1;
    fp1 = fopen("grades.txt","r");
    int i = 0,j;
    typedef struct
    {
        int number;
        int q[4];
        int total;
    } student;
    student a[101];
    while(feof(fp1) == 0)
    {
        if(i==0) i++;
        else
        {
            fscanf(fp1,"%d %d %d %d %d %d", &a[i].number, &a[i].q[0], &a[i].q[1], &a[i].q[2], &a[i].q[3], &a[i].total);
            printf("%d %d %d %d %d %d\n", a[i].number,a[i].q[0], a[i].q[1], a[i].q[2], a[i].total);
            i++;
        }
    }
    fclose(fp1);
    return 0;
}

However, it prints garbage values and segmentation fault error.

778121006 7632239 778121006 7632239 0 -1399308296
Segmentation fault

And the content of grades.txt is

grades.txt

ID       Q1 Q2 Q3 Q4 Total
20131122 20 14 18 22    74
20132400 16 23 11 19    69
Hyeonseo Kim
  • 324
  • 3
  • 15
  • 3
    See: [Why is “while ( !feof (file) )” always wrong?](http://stackoverflow.com/q/5431941/253056). Also you need to add error checking after your call to `fopen`. – Paul R May 31 '18 at 13:45
  • 3
    What Paul R writes. Also, you forget to skip the first line, which contains text, rather than numbers. – Yoric May 31 '18 at 13:46

2 Answers2

1

Firstly, you didn't check the return value of fopen() as if file doesn't exist your code shouldn't do further operation on fp1. So check the return value as

fp1 = fopen("grades.txt","r");
if(fp1 == NULL) {
   /* error handling */
}

Secondly, as mentioned by @paul Why is “while ( !feof (file) )” always wrong? , instead use fscanf() inside while loop & check the return value of fscanf() as

while(fscanf(fp1,"%d %d %d %d %d %d", &a[i].number, &a[i].q[0], &a[i].q[1], &a[i].q[2], &a[i].q[3], &a[i].total) == 6 ) { /* 6 is the no of read item */
      printf("%d %d %d %d %d \n", a[i].number,a[i].q[0], a[i].q[1], a[i].q[2], a[i].total);
      i++; 
}

Some silly mistakes you did as there was one extra %d inside printf() statement that you could have solved or observed while compiling with -Wall flag. This

printf("%d %d %d %d %d %d\n", a[i].number,a[i].q[0], a[i].q[1], a[i].q[2], a[i].total);

having six %d but you provided only 5 argument, remove extra %d as there are only 5 arguments.

Achal
  • 11,821
  • 2
  • 15
  • 37
0

You have to skip the first line. You increment i, but you dont skip the first line. You make the program read characters as ints. Perhaps something along the lines of

fscanf(fp1,"%s %s %s %s %s %s", ....(strings here) );

in the if block

kkica
  • 4,034
  • 1
  • 20
  • 40