Course contentsShow
← C
Lesson 681 of 1,21910. Input and OutputFree lesson

EOF (End Of File) explained

EOF (End Of File) explained

What you'll learn: You will understand how C programs recognize when there is no more data left to read from an input source.

The "Empty Bucket" Signal

In C, reading input is like taking water out of a bucket. You can keep scooping out characters as long as they are there. But how do you know when the bucket is bone-dry? Instead of returning a letter, the input function returns a special signal called EOF.

EOF stands for End Of File. It is not a character itself (it’s not a hidden 'A' or 'Z'), but rather a specific integer value—usually -1—defined in the <stdio.h> library. When a function like getchar() reaches the end of a file or a stream, it sends this value back to tell your program: "Stop looking; there’s nothing left!"

Watching for the Signal

Since EOF is an integer value and not a character, we must store the result of our input functions in an int variable, not a char. If we use a char, we might not be able to distinguish between a legitimate character and the EOF signal.

Here is how you typically use a loop to read until the data runs out:

#include <stdio.h>

int main() {
    int ch; // Use int, not char, to hold EOF

    printf("Type something (Press Ctrl+D or Ctrl+Z to stop):\n");

    // Keep getting characters until we hit EOF
    while ((ch = getchar()) != EOF) {
        putchar(ch);
    }

    printf("\nEnd of input reached. Goodbye!\n");
    return 0;
}

EOF in the Real World

If your program is reading a text file, EOF happens automatically when the computer hits the last byte of the file.

However, if you are typing directly into the console, the program will wait forever for more input because it thinks you might type more. You have to manually "send" the EOF signal using a keyboard shortcut. On Linux or macOS, you press Ctrl+D. On Windows, you press Ctrl+Z and then hit Enter. This tells the program that the "stream" of data is finished, triggering the EOF condition and ending the loop.

Key takeaway

EOF is a special integer value returned by input functions to signal that no more data is available to be read.