Detecting the end of a file with feof
What you'll learn: How to use the feof() function to determine when your program has reached the very end of a file.
The "Wall" at the end of the file
Imagine you are reading a book in a dark room with a small flashlight. You can see the words on the current page, but you don't know exactly how many pages are left. You only know you are finished when you try to turn a page and realize there are no more.
In C, when you open a file using fopen(), your program keeps track of a "cursor" (like a bookmark). As you read data, that cursor moves forward. The feof() function acts like a sensor that tells you if that cursor has bumped into the "End Of File" (EOF) marker.
How feof works
The function feof(file_pointer) returns a "true" value (non-zero) only after an input operation has tried to read past the end of the file.
A common mistake is thinking feof() looks ahead to see if the end is coming. It doesn't. It only reports the "End Of File" status based on the last read attempt. If you try to read a character and there is nothing left, the system sets an internal "EOF flag," and feof() then returns true.
Code Example: Reading until the end
Here is how you typically use it inside a loop to read a file character by character:
#include <stdio.h>
int main() {
FILE *fptr = fopen("notes.txt", "r");
if (fptr == NULL) return 1;
char ch;
// Read the first character
ch = fgetc(fptr);
// Keep looping as long as we haven't hit the end
while (!feof(fptr)) {
printf("%c", ch);
// Try to read the next character
ch = fgetc(fptr);
}
fclose(fptr);
return 0;
}
Why check after reading?
In the code above, we read a character, and then the while loop checks feof(). If fgetc hits the end of the file, feof() becomes true, and the loop stops immediately. This prevents your program from trying to process "empty" data that doesn't actually exist at the end of the stream.
Key takeaway
The feof() function returns true only after a reading command attempts to go past the last byte of a file.