Lesson 86 +10 XP

File Modes in Detail

The mode string in fopen decides everything: reading, writing, creating, or appending.

The main modes


c
"r"     read only (file must exist)
"w"     write only (creates or truncates)
"a"     append (creates or writes at the end)
"r+"    read + write (file must exist)
"w+"    write + read (creates or truncates)
"a+"    append + read

Reading and writing with r+


c

### FILE *file = fopen("data.txt", "r+");

Open existing file for both.

The '+' modes open both directions

Separate "r"/"w" only lets one direction; the plus opens both.

Binary modes

suffix b (like "rb") keeps the file binary-safe on Windows (doesn't mangle newlines).

TL;DR

  • "r" read, "w" write, "a" append.
  • Adding "+" allows both read and write.
  • "w" wipes; "a" appends.
  • "b" suffix is for binary safety.