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

23,637

Solution 1

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.

Solution 2

You should consider EOF conditions to be an implementation detail. What's really important here is whether fscanf has successfully returned a value.

while(fscanf(ifp, "%d", &test) == 1) {
    printf("%d\n", test);
}

On the other hand, this feels like one of those times where it makes sense to put the logic in the middle of the loop.

while(1) {
    int ret = fscanf(ifp, "%d", &test);
    if (ret != 1)
        break;
    printf("%d\n", test);
}

Especially for debugging, it can be nice to split things up into separate statements with variables that can be inspected.

Solution 3

For various reasons, it's impossible to determine if EOF has been reached without actually performing a prior read from the file.

However, using a seperate function call to do this is a bad idea, even if you were to use ungetc() to put back the character you tried to read.

Instead, check the return value of the call to fscanf() itself:

while(fscanf(ifp, "%d", &test) == 1)
{
    printf("%d\n", test);
}

Solution 4

How about simply:

while (fscanf (ifp, "%d", &test) != EOF)
    printf("%d\n", test);

Solution 5

fgetc(ifp) advance the file pointer, hence skipping your first integer

Instead Use: -

while(1)
{

    if(fscanf(ifp, "%d", &test)!=1) 
         break;
    printf("%d\n", test);
}
Share:
23,637
Karim Elsheikh
Author by

Karim Elsheikh

Updated on February 11, 2020

Comments

  • Karim Elsheikh
    Karim Elsheikh over 4 years

    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!