Nearby lessons

119 of 124

C - 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
CCode Cell
1#include <stdio.h>
2 
3void main()
4{
5 FILE *fp = fopen("marks.txt", "w");
6 if (fp == NULL) { printf("Cannot open\n"); return; }
7 
8 fprintf(fp, "Rahul 88\n"); // write formatted data
9 fprintf(fp, "Priya 95\n");
10 fputs("Anil 76\n", fp); // write a string
11 
12 fclose(fp);
13 printf("File written\n");
14}
Output
File written
📝 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 Questions
Progress: 0 / 1