file-handling · beginner · ~10 min
Use append mode to add to a file without truncating it.
Append a line of text to the end of a file without disturbing what's already there — how logs and audit trails grow.
Implement int append_line(const char *path, const char *line) that opens path in append mode, writes line followed by a newline, then closes the file.
path: filename of a file in the working directory (created if it doesn't exist).line: the text to append (without a newline; you add it).Return the number of bytes written, which is strlen(line) + 1 (the line plus the newline). Return -1 if path or line is NULL, or the file can't be opened.
append_line("al.txt", "first") -> 6
append_line("al.txt", "second") -> 7
file "al.txt" now contains "first\nsecond\n"
append_line(NULL, "x") -> -1
"a"), never truncate ("w" would erase existing content).Append mode is how logs and audit trails grow without clobbering existing content.
path: file to append to (created if absent). line: text to add (no newline).
int bytes written (strlen(line)+1), or -1 on NULL arg / open failure.
Open in append mode; do not truncate; write the newline yourself.
#include <stdio.h>
int append_line(const char *path, const char *line) {
/* TODO */
(void)path; (void)line;
return -1;
}
Using "w" (truncates the file). Forgetting the newline. Not closing on failure.
First write creates the file. NULL path or line → -1.
O(len).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.