Nearby lessons
120 of 124C - Reading from a File
Reading from a File is one of the foundational topics in C programming. This lesson explains Reading from a File and End of File — EOF with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Reading from a File
Use fscanf (like scanf, reads formatted data) and fgets (reads a whole line). fgets returns NULL when the file ends — that is how we know when to stop.
fscanf returns the number of values it read. When it returns 2, a record was read successfully. When the file ends, it returns EOF (-1), so the loop stops.
Trainer's Note: Reading a whole line (with spaces) uses fgets(line, size, fp) — the same safe line reader we met for keyboard input in Chapter 8. fscanf %s reads only one word per field, which suits records with separate name and marks columns.
Example01
End of File — EOF
EOF (End Of File) is a special constant (value -1) that tells you the file has ended. You can also write the reading loop like this:
Example02
📝 Key Takeaways
- Files save data permanently; use FILE * and stdio.h functions.
- Open with fopen(mode), close with fclose — always check fp == NULL.
- Modes: r (read), w (write, erases old), a (append, keeps old).
- Write with fprintf/fputs; read with fscanf/fgets/fgetc.
- fscanf returns the count read; EOF (-1) marks the end of the file.
- Character copy: while ((ch = fgetc(in)) != EOF) fputc(ch, out).
🧠 Test Your Knowledge
2 QuestionsProgress: 0 / 2