Nearby lessons

114 of 124

C - File Handling

File Handling is one of the foundational topics in C programming. This lesson explains Why Files? and Opening and Closing a File with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Why Files?

When a program ends, everything in memory is lost. Files let us save data permanently — on the hard disk — so it can be read later by the same or another program. Think of files as a permanent notebook for your program.

In C, we work with files using functions from stdio.h, a special pointer type called FILE *, and a stream called stdin (keyboard) and stdout (screen).

In simple words: memory forgets when the program stops; files remember forever. A file is the program's permanent notebook — write today, read tomorrow, even by a different program.

Opening and Closing a File

In simple words: fopen is booking a room — "r" means I will read only, "w" means give me a fresh empty room (old stuff thrown out), "a" means let me add to the room, keep what is inside. fclose locks the room when you leave.
Example02
CCode Cell
1FILE *fp; // file pointer
2fp = fopen("data.txt", "w"); // open for writing
3if (fp == NULL) { // always check!
4 printf("Cannot open file\n");
5 return;
6}
7// ... work with the file ...
8fclose(fp); // always close
📝 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

3 Questions
Progress: 0 / 3