Nearby lessons
121 of 124C - Append to a File
Appending adds to the end of a file without touching what is already there. Learn the "a" and "a+" modes, why every write goes to the end regardless of position, and how appending powers log files and running records.
Appending With "a"
Open with "a", write, close. Whatever was in the file stays:
"a" vs "w" — The Whole Point
"w" means "this file is now mine, start fresh". "a" means "keep everything and add to the bottom". Choosing the wrong one is the difference between a log file and an empty file."a" | "w" | |
|---|---|---|
| Existing content | Preserved | Erased |
| Starting position | End of file | Beginning |
| Missing file | Created | Created |
| Can read | No | No |
| Use for | Logs, running records | Fresh output |
Writes Always Go to the End
fseek cannot move where you write. The standard requires every write to be repositioned to the end of the file first, so seeking to byte 0 and writing still appends. This surprises people trying to update a record in place — for that you need "r+", not "a+"."a+" — Append and Read
"a+" adds reading. The read position moves freely; the write position does not:
Appending Creates a Missing File
You never need to check whether the file exists first — "a" handles both cases:
A Timestamped Log
The most common real use of append mode. Each run adds to the record instead of replacing it:
Appending Structured Records
Appending is not limited to text lines — a CSV or binary record file grows the same way:
Appending Binary Records
Use "ab" for binary. Fixed-size records make the file a simple growing array:
Keeping a Log From Growing Forever
An append-only file never shrinks. Check the size occasionally and start fresh when it gets too large:
Common Mistakes
- Using
"w"when you meant"a"— the existing contents are erased atfopen. - Expecting
fseekto work for writing — in append mode every write goes to the end. - Trying to read in mode
"a"— use"a+". - Forgetting the newline —
fprintf(fp, "text")runs entries together on one line. - Not closing between appends — a crash then loses the buffered entries.
- Letting a log grow unbounded — rotate it by size or by date.
- Expecting
"a+"to update records in place — you need"r+"for that.
- Mode "a" opens for appending and creates the file if it is missing.
- Every write in append mode goes to the end, whatever fseek says.
- Unlike "w", appending never destroys existing content.
- "a+" allows reading as well, but writes still land at the end.
- Appending is the natural mode for logs and accumulating records.