Back to Blog

C in 100 Seconds: File I/O Writing

Daryl WongDaryl Wong

Video: C in 100 Seconds: File I/O Writing — fprintf, fputs, Append | Episode 36 by Taught by Celeste AI - AI Coding Coach

Watch full page →

File I/O — Writing

Writing files in C follows the same open-use-close pattern as reading. The key difference is the mode you pass to fopen.

fprintf — Formatted Writing

FILE *f = fopen("/tmp/output.txt", "w");
fprintf(f, "Name: %s
", "Alice");
fprintf(f, "Age: %d
", 30);
fprintf(f, "Score: %.1f
", 95.5);
fclose(f);

fprintf works exactly like printf but writes to a file instead of the screen. Open with "w" mode to create a new file or overwrite an existing one.

fputs — Plain String Writing

FILE *f2 = fopen("/tmp/notes.txt", "w");
fputs("First line
", f2);
fputs("Second line
", f2);
fclose(f2);

When you just need to write a string without formatting, fputs is simpler than fprintf.

Append Mode

FILE *f3 = fopen("/tmp/notes.txt", "a");
fputs("Appended line
", f3);
fclose(f3);

Open with "a" instead of "w" to add data to the end of an existing file. Nothing gets overwritten.

The Three Modes

  • "w" — write (create or overwrite)
  • "a" — append (add to end)
  • "r" — read (from Episode 35)

Student Code

Try it yourself: episode36/writefile.c