C/C++ Arena

Step 5 of 8

Appending

Opening a file with "w" erases whatever was in it. When you want to add to a file instead, like a log that grows over time, use "a" (append): the file is created if it doesn't exist, and every write goes to the end, keeping the existing contents.

#include <stdio.h>

int log_event(const char *path, const char *event, int value) {
    FILE *f = fopen(path, "a");
    if (f == NULL) {
        return -1;
    }
    fprintf(f, "%s=%d\n", event, value);
    fclose(f);
    return 0;
}

int main(void) {
    log_event("events.log", "start", 1);
    log_event("events.log", "score", 40);
    log_event("events.log", "end", 1);
    FILE *f = fopen("events.log", "r");
    if (!f) return 1;
    char line[64];
    while (fgets(line, sizeof line, f)) {
        fputs(line, stdout);
    }
    fclose(f);
    return 0;
}
start=1
score=40
end=1

Each call opens, appends one line, and closes. Three calls, three lines, none lost. With "w" only the last line would survive.

fputs(s, f) writes a string as is (no formatting and no added newline). Writing to stdout sends it to the screen.

Other modes

Mode Meaning
"r+" read and write an existing file
"w+" read and write, creating or emptying the file
"rb", "wb", "ab" binary versions: no newline translation (matters on Windows, and for non-text data)

Choosing the wrong mode is a classic data-loss bug: opening an important file with "w" "just to read it" empties it instantly.

Your turn: write int append_line(const char *path, const char *line) that appends line plus a newline. Return 0 on success and -1 if the file can't be opened.

Previous: Loading records Next: Safe formatting with snprintf