Lesson 86 +10 XP

File Modes in Detail

File Modes in Detail

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

The main modes

"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+

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

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.