The second argument of fopen selects the mode. "r" reads an existing file, "w" creates or truncates for writing, and "a" appends at the end. Adding + allows both reading and writing, and adding b selects binary mode ("rb", "wb"). Writing modes create the file if it does not exist, except "r" and "r+".
Remember
"r" read, must exist "r+" read/write, must exist
"w" write, truncate/create "w+" read/write, truncate
"a" append, create "a+" read/append
add b for binary: "rb" "wb" "ab"
Reference
Cheat Sheet
Keep these facts handy while you work with File Modes in C.
Topic
Detail
r
File must exist
w
Destroys previous content
a
Always writes at the end
b
Binary, no newline translation
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Reading Text Files.
Example 1 — Create, append, and read back
Compare "w" and "a".
C
#include <stdio.h>
int main(void) {
FILE *fp = fopen("modes.txt", "w");
if (!fp) return 1;
fputs("line1\n", fp);
fclose(fp);
fp = fopen("modes.txt", "a");
if (!fp) return 1;
fputs("line2\n", fp);
fclose(fp);
char buf[32];
fp = fopen("modes.txt", "r");
if (!fp) return 1;
while (fgets(buf, sizeof buf, fp)) printf("%s", buf);
fclose(fp);
return 0;
}
Output
line1
line2
How It Works
"w" starts the file with line1.
"a" keeps line1 and adds line2 at the end.
Opening with "w" again would erase both lines.
Edge Cases & Pitfalls
Check these before relying on File Modes in real programs.
trunc
Truncating by accident
"w" and "w+" delete existing content immediately.
switch
Switching between read and write
With + modes you must call fflush or a positioning function (fseek, rewind) between a write and a read.
Remember
Key Takeaways
w: destructive.
a: safe for logs.
b: use for non-text data.
One line: The second argument of fopen selects the mode.
Frequently Asked Questions
w truncates the file to zero length before writing; a keeps existing content and writes new data at the end.
On Windows, to prevent newline translation for non-text data. On POSIX systems it has no effect but is harmless and portable.
Continue with "C Reading Text Files" next. Read lines and characters with fgets and fgetc. The C File Handling hub lists every topic in order.