Nearby lessons
115 of 124C - File Modes
File Modes is one of the foundational topics in C programming. This lesson explains The File Modes with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
The File Modes
| Mode | Meaning | What happens |
|---|---|---|
| "r" | Read | Opens for reading; error if the file does not exist |
| "w" | Write | Opens for writing; creates new or erases old content |
| "a" | Append | Opens for writing; adds at the end, keeps old content |
| "r+" | Read + write | Existing file |
| "w+" | Read + write | New file (erases old) |
Trainer's Note: The "w" mode is dangerous if used carelessly — it wipes the existing file content. Use "a" to add to a file without losing what is already there.
📝 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