0

My program should read some segments to id a plane. 3 segments per line. The input archive is:

3 4 25 -4 -30 2 6 7 9 10 3 4
3 4 4 -4 -3 2 6 7 9 10 5 6

and it is read as coordinates: (3, 4) (25, -4) (-30, 2) (6,7) (9,10) (3,4)

A Segment would be a pair of coordinates: S01 - (3,4) (25, -4) and so on

the code:

typedef struct{
    int x1, x2;
    int y1, y2;
    int id;    
}Segment;

int main(){

    FILE *file;
    int i=0, j=0;
    Segment *seg;

   seg=(Segment*)malloc(500*sizeof(Segment));

   file = fopen("input.txt", "r"); 

    while(!feof(file)){

        for(i=0; i<3; i++){
                fscanf(file, "%d %d %d %d", &seg[j].x1, &seg[j].y1,  &seg[j].x2, &seg[j].y2);
                seg[j].id=i+1;
                printf("%d %d %d %d - ID: %d\n", seg[j].x1, seg[j].y1,  seg[j].x2, seg[j].y2, seg[j].id);
                j++;
        }
    }   
    fclose(file);

    return 0;
}

the expected output:

 3 4 25 -4 - ID: 1
 -30 2 6 7 - ID: 2
 9 10 3 4 - ID: 3
 3 4 4 -4 - ID: 1
 -3 2 6 7 - ID: 2
 9 10 5 6 - ID: 3

The output it gives me, I do not know why:

3 4 25 -4 - ID: 1
-30 2 6 7 - ID: 2
9 10 3 4 - ID: 3
3 4 4 -4 - ID: 1
-3 2 6 7 - ID: 2
9 10 5 6 - ID: 3
0 0 0 0 - ID: 1
0 0 0 0 - ID: 2
0 0 0 0 - ID: 3

I know this must be some silly mistake, but any ideas of what is causing it?! Thanks in advance :)

Laura Martins
  • 583
  • 2
  • 6
  • 15

1 Answers1

5

You should test the return value of fscanf(), which must be 4. Moreover, you do not use feof() the right way "see why is while (!feof(file)) always wrong: it is used to test if the last reading function (fread(), fscanf()...) failed on an end of file (see feof(3) and ferror(3))

Edit: So your code should be like:

 while (fscanf(...) == 4)
 {
      // do things with data
 }

 // after reading loop, determine why it ended
 if (feof(f))
 {  
     // end of file reached
 }
 else if (ferror(f))
 {  
     // error while reading
 }
 else
 {  
     // fscanf failed, syntax error ?
 }
Community
  • 1
  • 1
Mathieu
  • 8,840
  • 7
  • 32
  • 45