Writing Files
Writing reuses the open/write/close shape from reading. Just swap the mode string and reach for output functions instead of input ones.
Opening for Writing
FILE *fp = fopen("output.txt", "w"); // truncate and writeif (fp == NULL) { perror("Failed to open file"); return 1;}"w"creates the file if it does not exist and truncates it if it does."a"opens for appending - writes go to the end without truncating."w+"opens for both reading and writing.
Worked Example: Four Modes, One File
The mode decides what happens to the bytes already in the file, and that's easiest to see side by side. Start each time with notes.txt holding the four bytes old\n, open it with a different mode, write one string and close it:
| Mode | Write | File afterwards | Why |
|---|---|---|---|
"w" | NEW\n | NEW\n | truncated to 0 bytes on open, then written |
"a" | NEW\n | old\nNEW\n | every write goes to the current end |
"r+" | N | Nld\n | starts at byte 0 and overwrites in place, no truncation |
"wx" | (none) | old\n | fopen returns NULL because the file exists |
The "r+" row catches people out. Writing one byte at the start replaces exactly one byte, so the o becomes N and the rest stays. Nothing shifts along to make room; files don't have an insert operation. "r+" also fails if the file doesn't exist, unlike "w" and "a", which create it.
The x suffix arrived in C11. "wx" refuses to touch a file that's already there, which makes it the safe choice when overwriting someone's data would be a bug. On Linux the failure sets errno to EEXIST, so perror prints File exists.
Predict: open notes.txt (still holding old) with "a", call fseek(fp, 0, SEEK_SET) to jump back to the start, then write X and a newline. Where does the X land?
At the end: the file becomes old\nX\n. In append mode the C standard forces every write to the then-current end of file, whatever the position was before. fseek still matters for reading in "a+" mode, but it can't make an append-mode write overwrite anything.
Writing Text
fprintf(fp, "Name: %s\n", "Alice");fprintf(fp, "Score: %d\n", 95);fputs("End of record\n", fp);fputc('\n', fp);Flushing and Closing
Data written to a file may sit in a buffer before being written to disk:
fflush(fp); // hand stdio's buffer to the kernel (not necessarily to disk yet)fclose(fp); // flushes and closesIf your program crashes between writing and closing a file, buffered data may be lost. For critical data, call fflush after important writes. That only protects you against your own process dying, though: the data is now in the kernel's page cache, which survives a crash but not a power cut. To get it onto the physical disk you need fsync (POSIX) on the file descriptor as well.
Line the failures up against the layers and the rule falls out. Each layer survives the failures below it in this chart and loses to the ones above:
A process crash can't touch the page cache, because the kernel owns it, not your process. A power cut takes everything that hasn't reached the disk, however many times you called fflush.
Error Checking
Always check the return value of write operations:
if (fprintf(fp, "data\n") < 0) { perror("Write failed");}Practical Pattern: Configuration File
void save_config(const char *filename, int width, int height) { FILE *fp = fopen(filename, "w"); if (!fp) { perror("save_config"); return; } fprintf(fp, "width=%d\n", width); fprintf(fp, "height=%d\n", height); fclose(fp);}Serialising data to a text file like this is the bedrock of plenty of persistence mechanisms, the key-value store we'll build in the capstone included.
There's a flaw, though. "w" truncates the old config before the new one is written, so a crash halfway through leaves a half-written file and no backup. The standard fix writes to a temporary file and then renames it over the original. On POSIX systems rename replaces the target in one step, so a reader sees either the old file or the new one, never a mix.
You'll meet this exact pattern again in the capstone's persistence lesson.