Nearby lessons
119 of 124C - Writing to a File
Writing to a File is one of the foundational topics in C programming. This lesson explains Writing to a File with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Writing to a File
Use fprintf (like printf, but writes to the file) and fputs (like puts, for strings):
After running, a file named marks.txt is created with three lines.
Example01
📝 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
1 QuestionsProgress: 0 / 1