Nearby lessons
114 of 124C - 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
📝 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 QuestionsProgress: 0 / 3