Nearby lessons

115 of 124

C - 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

ModeMeaningWhat happens
"r"ReadOpens for reading; error if the file does not exist
"w"WriteOpens for writing; creates new or erases old content
"a"AppendOpens for writing; adds at the end, keeps old content
"r+"Read + writeExisting file
"w+"Read + writeNew 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 Questions
Progress: 0 / 2