🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →EOF in C Explained Simply
How a C program learns that a file has ended, why EOF is not a character, and the standard shape of every file program.
Reading a file in a loop only works if the loop knows when to stop. That signal is called end of file, and understanding EOF in C removes a whole family of beginner bugs: loops that run once too often, programs that stop early on perfectly good data, and tools that hang waiting for input. This lecture of our free C programming course explains what EOF really is, how it travels from the operating system to your code, and how to write the standard skeleton that every file program follows.
The source book states that the operating system “sends a signal” when the end is reached. That wording is misleading for modern systems, so we correct it here. There is no signal and no special character. As in the previous lecture, every program was built with gcc -Wall -Wextra and the output shown is genuine.
What You Will Learn
In this free C tutorial you will:
- Describe EOF in C as a return value, not as data stored in the file.
- Trace how end of file moves from the kernel through stdio into your loop.
- Use
feof(),ferror()andclearerr()correctly. - Reproduce and fix the classic
while(!feof(fp))bug. - Write the open, check, use, test, close skeleton used in embedded C programming.
Prerequisites
You need to know how to open a file with fopen(), how to close it with fclose() (the previous lecture) and what a loop is. Knowing that a function can return a special value to signal failure is enough background.
What EOF in C Actually Is
EOF is a macro defined in <stdio.h>. The C standard requires it to be a negative integer constant expression, and on practically every platform it equals -1. You can print it yourself, as the first line of the program below does. The important idea is in the name of the role it plays: EOF is what a reading function returns when it cannot give you another item. It is never written into the file.
Common wrong picture
Many beginners imagine a special byte sitting at the end of every file. Files do not work that way. A file is just N bytes plus a stored length. Nothing is appended to mark the end.
The journey of an end-of-file condition
When your program asks for more bytes at the end of a file, the operating system answers a read() request with the number zero, meaning “zero bytes available”. The C library notices this, sets an internal end-of-file indicator on the FILE object, and makes your call to fgetc() return EOF.
How end of file reaches your loop
The last line of the diagram matters. EOF is returned in two different situations, a normal end and a failure. The return value alone cannot tell them apart, which is why C gives you two query functions.
feof, ferror and clearerr: The Three Helpers
| Function | Returns non-zero when | Typical use |
|---|---|---|
feof(fp) | The end-of-file indicator is set | After a read returned EOF, to confirm a normal end |
ferror(fp) | The error indicator is set | After a read returned EOF, to detect a failed read |
clearerr(fp) | (returns nothing) | Reset both indicators before reading again |
The clean pattern is: loop on the return value of the read function, and only when the loop ends ask ferror() whether it ended badly. You will see this exact pattern in the template program later in this lecture.
The Classic while(!feof) Bug in Practice
The most copied mistake in beginner C code is looping on feof(). To see why it fails, the next program writes the three characters xyz, then reads them back twice: once with the correct loop and once with the buggy one.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("abc.txt", "w");
if (!fp)
return EXIT_FAILURE;
fputs("xyz", fp);
fclose(fp);
printf("EOF is the integer %d\n\n", EOF);
/* Correct: test the value returned by the read call itself */
fp = fopen("abc.txt", "r");
int c, good = 0;
while ((c = fgetc(fp)) != EOF)
good++;
printf("correct loop : %d iterations\n", good);
fclose(fp);
/* Wrong: test feof() before the read has failed */
fp = fopen("abc.txt", "r");
int bad = 0;
while (!feof(fp)) {
c = fgetc(fp);
bad++;
printf(" iteration %d got value %d\n", bad, c);
}
printf("feof loop : %d iterations (one too many)\n", bad);
fclose(fp);
return 0;
}
gcc -Wall -Wextra -o ep_eof ep_eof.c
./ep_eof
EOF is the integer -1
correct loop : 3 iterations
iteration 1 got value 120
iteration 2 got value 121
iteration 3 got value 122
iteration 4 got value -1
feof loop : 4 iterations (one too many)
Read the output slowly. Values 120, 121 and 122 are the ASCII codes of x, y and z. At the start of the fourth iteration feof() is still false, because no read has failed yet. The call inside the loop then fails, returns -1 and sets the flag, but the loop body has already started and treats -1 as data. In a real program that extra pass duplicates the last record or processes garbage. This is the practical meaning of EOF in C: the end is learned from the read result, not predicted beforehand.
Which Functions Report EOF, and How
| Function | Signals end of file by | Safe loop condition |
|---|---|---|
fgetc, getc, getchar | Returning EOF | (c = fgetc(fp)) != EOF |
fgets | Returning NULL | fgets(buf, n, fp) != NULL |
fscanf | Returning fewer items than requested, or EOF for input failure | fscanf(fp, "%d", &x) == 1 |
fread | Returning a count smaller than requested | fread(buf, size, 1, fp) == 1 |
getw | Returning EOF (ambiguous with the value -1) | Call feof() and ferror() after each call |
Because EOF is an ordinary int value, the variable that receives it must be an int as well. The reason is explained in detail in the lecture on fgetc(); for now, remember to declare int c, never char c.
Sending EOF From the Keyboard
When a program reads from the keyboard there is no file to run out. The terminal driver supplies the end instead. On Linux and macOS, press Ctrl+D on an empty line. On a Windows console, press Ctrl+Z and then Enter. Neither key stores a character in your data; they only make the next read return zero bytes. When input comes through a pipe, as in printf 'abc' | ./prog, the end arrives automatically when the left-hand program exits.
Embedded tip
On a microcontroller where stdin is connected to a UART, there is no natural end of input at all. The retargeted read routine decides what “end” means, perhaps a timeout or a special command. Never assume a terminal-style Ctrl+D exists on the target.
The Standard Structure of a File Program
Almost every file program in C follows the same five steps. The old book shows only the first and last, with dots in between. The version below is complete and safe enough to reuse.
Skeleton of a safe file program
The next program, ep_count, counts lines and characters of a file given on the command line. It follows the skeleton exactly and uses the return value of fgetc() as the loop condition.
#include <stdio.h>
#include <stdlib.h>
/* The standard shape of every file program: open, check, use, close. */
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "usage: %s <file>\n", argv[0]);
return EXIT_FAILURE;
}
FILE *fp = fopen(argv[1], "r");
if (fp == NULL) {
perror(argv[1]);
return EXIT_FAILURE;
}
long chars = 0, lines = 0;
int c;
while ((c = fgetc(fp)) != EOF) {
chars++;
if (c == '\n')
lines++;
}
if (ferror(fp)) {
perror("read");
fclose(fp);
return EXIT_FAILURE;
}
fclose(fp);
printf("%s: %ld lines, %ld characters\n", argv[1], lines, chars);
return EXIT_SUCCESS;
}
gcc -Wall -Wextra -o ep_count ep_count.c
printf 'one\ntwo\nthree\n' > sample.txt
./ep_count sample.txt
./ep_count nofile.txt
./ep_count
sample.txt: 3 lines, 14 characters
nofile.txt: No such file or directory
usage: ./ep_count <file>
The file holds 14 characters: three words of 3, 3 and 5 letters plus three newlines. The second run shows fopen() failing, and perror() explains why. The third run, with no argument, prints a usage message. Each failing path returns EXIT_FAILURE, which is how scripts and build systems learn that something went wrong.
Why the book’s skeleton is not enough
- It writes
main()without a return type and omits the return value; modern C requiresint main(void). - It does not test
fopen()forNULL, so a missing file crashes the program. - It never checks
ferror(), so a read failure looks like a normal end. - It prints nothing to explain failure;
perror()costs one line and saves hours.
Real-World Embedded Uses of EOF
- Configuration loaders: a Linux gateway reads
key=valuelines untilfgets()returnsNULL. - Log analysers: a tool scans an event log, then calls
ferror()to be sure it did not stop on a bad flash sector. - Firmware image checks: a checksum routine reads a binary image in blocks until
fread()returns a short count. - Tail-style monitors: a diagnostics daemon reaches EOF on a growing log, calls
clearerr(), waits, and reads the new lines.
Common Mistakes and Troubleshooting
| Mistake | What happens | Fix |
|---|---|---|
Looping on while(!feof(fp)) | One extra iteration with garbage | Loop on the read function’s return value |
Storing fgetc() in a char | Early stop or endless loop, depending on the target | Use int |
Ignoring ferror() | A damaged file looks like a short, valid file | Check it after the loop |
Reading again after EOF without clearerr() | Every call keeps returning EOF | Call clearerr() first |
| Assuming the last line ends with a newline | Last record silently dropped | Handle a final line without \n |
Best Practices for EOF in C
- Make the read call part of the loop condition, so there is no second read to forget.
- Always hold the result in an
int. - After the loop, distinguish
ferror()from a normal end, and report errors withperror(). - Return
EXIT_SUCCESSorEXIT_FAILUREfrommain()so callers can react. - Treat every input file as untrusted: do not assume a size, a final newline or a valid record at the end.
Performance and security notes
Reading one character per call is simple but slow for large files because each call has overhead; later lectures show block reads with fread(). On the security side, a program that trusts a file to end where it expects can be driven into reading past a buffer. Always check the number of items actually read, and never use the absence of EOF as proof that data is valid.
Key Takeaways
Remember these points
- EOF in C is a negative
intreturned by reading functions, not data in the file. - The kernel reports the end with a zero-byte read; stdio converts it to
EOF. EOFalso signals errors, so follow up withferror().- Never loop on
feof(); loop on the read result. - Ctrl+D (Linux) and Ctrl+Z (Windows) end terminal input but are not stored.
- Every file program is: open, check, loop, test errors, close.
Conclusion
You now know that EOF is information delivered by a function, that it can mean two different things, and that the safest loops let the read call itself decide when to stop. The extra-iteration experiment made the old while(!feof()) mistake visible, and the ep_count program gave you a skeleton to copy into your own embedded projects.
In the next lecture of this free embedded C course we meet the three streams that exist before your program even starts, stdin, stdout and stderr, and see how they connect to a terminal, a file or a UART.
Frequently Asked Questions
What is EOF in C?
EOF is a macro from <stdio.h> that expands to a negative integer constant, normally -1. Reading functions return it to tell you that no more data is available or that an error happened. It is a return value, not a byte stored in the file.
Is EOF a character at the end of the file?
No. A file is only a sequence of bytes with a length. The system knows the file ended because a read request returns zero bytes. The C library turns that into the value EOF for your program.
Why is while(!feof(fp)) wrong?
feof() becomes true only after a read has already tried to go past the end. The loop therefore runs once more than it should and processes a failed read as if it were data. Test the return value of the read call itself instead.
How do I tell end of file from a read error?
When a reading function returns EOF, call ferror(fp). A non-zero result means a real error; otherwise call feof(fp) to confirm a normal end of file.
How do I send EOF from the keyboard?
Press Ctrl+D on an empty line in a Linux or macOS terminal, or Ctrl+Z followed by Enter in a Windows console. The terminal driver reports end of input; no special byte is stored.
Why must the variable holding the result be an int?
A byte read from a file can be any of 256 values, and EOF is one more value outside that range. A char cannot represent all 257 possibilities, so one real byte may be confused with EOF or the end may never be detected.
Can I read a stream again after EOF?
Call clearerr(fp) to reset the end-of-file and error indicators. This is useful for a log file that another process keeps appending to, or for a terminal after the user pressed Ctrl+D.
Continue the Free C Programming Course
Next up: the standard streams, then character input and output with fputc and fgetc, and a complete embedded logging lab.

2 Comments