Stanfrancisco
Stanfrancisco

Reputation: 352

C - How to read file of integers until the end of the file

I am creating a program that reads in values from an input file and stores them into a 2d array.. I can't figure out how to end the "read in" loop at the end of the file, because I'm using integers and EOF isn't an integer.

Currently it will create an infinite loop.

//      while(?????)
     {
            //printf("Test");
            fscanf(fp, "%d", &x);
            fscanf(fp, "%d", &y);
            fscanf(fp, "%d", &val);
            fscanf(fp, "%d", &val2);
            fscanf(fp, "%d", &price);
            grid[x][y] = 1;
            grid[y][x] = 1;
     }

SAMPLE FILE INPUT

0 3 300 305 20
0 4 300 313 20
0 5 300 306 20
0 2 300 301 20
1 0 301 302 20
1 5 304 308 8
1 4 310 315 20
2 5 312 324 30

Upvotes: 2

Views: 1335

Answers (2)

user3121023
user3121023

Reputation: 8286

As long as the fscanf reads five values, the while will continue and will stop when it reaches the end of the file.

while( ( fscanf ( fp, "%d %d %d %d %d", &x, &y, &val, &val2, &price)) == 5)
{
    grid[x][y] = 1;
    grid[y][x] = 1;
}

Upvotes: 3

fferri
fferri

Reputation: 18940

Use !feof(fp) as the condition for your while loop

Upvotes: -1

Related Questions