Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if the file pointer has reached EOF without moving the file pointer?

my question is simple, but I can't find it on google, so here I am.

Basically, as an example, I am reading in a bunch of integers until EOF from an input file. I used fgetc to check, but then it moves the file pointer to the address of the 2nd integer. How can I check for EOF in this while loop without moving the file pointer when it checks?

Keep in mind I will be doing something much more complex with this loop than scanning in integers. Also, don't mention my use of fscanf rather than fgets, I know. Its just a simple example to show you what I mean.

while(fgetc(ifp) != EOF)
{

    fscanf(ifp, "%d", &test);
    printf("%d\n", test);
}

If the input file has integers 1-10 for example, the above code would print:

2 3 4 5 6 7 8 9 10

Missing the 1!

like image 521
Karim Elsheikh Avatar asked Nov 30 '22 12:11

Karim Elsheikh


1 Answers

fgetc Returns the character currently pointed by the internal file position indicator of the specified stream. The internal file position indicator is then advanced to the next character.Using do{ }while(); will solve your problem.

like image 179
Dayal rai Avatar answered Dec 04 '22 12:12

Dayal rai