file-handling · beginner · ~10 min

Append a line to a file

Use append mode to add to a file without truncating it.

Challenge

Append a line of text to the end of a file without disturbing what's already there — how logs and audit trails grow.

Task

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.

Input

  • 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).

Output

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.

Example

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

Edge cases

  • First write creates the file.
  • NULL path or NULL line: -1.

Rules

  • Use append mode ("a"), never truncate ("w" would erase existing content).

Why this matters

Append mode is how logs and audit trails grow without clobbering existing content.

Input format

path: file to append to (created if absent). line: text to add (no newline).

Output format

int bytes written (strlen(line)+1), or -1 on NULL arg / open failure.

Constraints

Open in append mode; do not truncate; write the newline yourself.

Starter code

#include <stdio.h>
int append_line(const char *path, const char *line) {
    /* TODO */
    (void)path; (void)line;
    return -1;
}

Common mistakes

Using "w" (truncates the file). Forgetting the newline. Not closing on failure.

Edge cases to handle

First write creates the file. NULL path or line → -1.

Complexity

O(len).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.