Brandon
Brandon

Reputation: 401

Does feof() work when called after reading in last line?

I just read in a string using the following statement:

fgets(string, 100, file);

This string that was just read in was the last line. If I call feof() now will it return TRUE? Is it the same as calling feof() right at the start before reading in any lines?

Upvotes: 2

Views: 2437

Answers (3)

chqrlie
chqrlie

Reputation: 144715

The short answer is NO. Here is why:

If fgets successfully read the '\n' at the end of the line, the end-of-file indicator in the FILE structure has not been set. Hence feof() will return 0, just like it should before reading anything, even on an empty file.

feof() can only be used to distinguish between end-of-file and read-error conditions after an input operation failed. Similarly, ferr() can be used to check for read-error after an input operation failed.

Programmers usually ignore the difference between end-of-file and read-error. Hence they only rely on checking if the input operation succeeded or failed. Thus they never use feof(), and so should you.

The behavior is somewhat similar as that of errno: errno is set by some library functions in case of error or failure. It is not reset to 0 upon success. Checking errno after a function call is only meaningful if the operation failed and if errno was cleared to 0 before the function call.

If you want to check if you indeed reached to the of file, you need to try and read extra input. For example you can use this function:

int is_at_end_of_file(FILE *f) {
    int c = getc(file);
    if (c == EOF) {
        return 1;
    } else {
        ungetc(c, file);
        return 0;
    }
}

But reading extra input might not be worthwhile if reading from the console: it will require for the user to type extra input that will be kept in the input stream. If reading from a pipe or a device, the side effect might be even more problematic. Alas, there is no portable way to test if a FILE stream is associated with an actual file.

Upvotes: 1

chux
chux

Reputation: 153417

Does feof() work when called after reading in last line?

No.

feof() becomes true when reading past the end of data. Reading the last line may not be pass the end of data if the last line ended in '\n'.

Upvotes: 2

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

No, don't use feof() to detect the end of the file. Instead check for a read failure, for example fgets() will return NULL if it attempts to read past the end of the file whereas feof() will return 0 until some function attempts to read past the end of the file, only after that it returns non-zero.

Upvotes: 2

Related Questions