file-handling · beginner · ~10 min

Append a line to a file

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

Challenge

Your job

int append_line(const char *path, const char *line);

Open path in append mode, write line followed by a newline, close. Return the number of bytes written (strlen(line) + 1), or -1 on NULL args or open failure.

Hints

  1. fopen(path, "a").
  2. fprintf(f, "%s\n", line) returns the count written.

Why this matters

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

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.