Nearby lessons

120 of 124

C - 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
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 FILE *fp = fopen("marks.txt", "r");
6 if (fp == NULL) { printf("Cannot open\n"); return; }
7 
8 char name[30];
9 int marks;
10 
11 // read records one by one until the end of file
12 while (fscanf(fp, "%s %d", name, &marks) == 2) {
13 printf("%s got %d\n", name, marks);
14 }
15 fclose(fp);
16}
Output
Rahul got 88 Priya got 95 Anil got 76

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
CCode Cell
1while (!feof(fp)) { // while NOT end of file
2 if (fscanf(fp, "%s %d", name, &marks) == 2)
3 printf("%s %d\n", name, marks);
4}
📝 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 Questions
Progress: 0 / 2