file-handling · intermediate · ~12 min

Take the last N lines

Locate a suffix of lines and copy it within bounds.

Challenge

Your job

int tail_lines(const char *text, int n, char *out, size_t cap);

Copy the last n lines of text into out (NUL-terminated), preserving their trailing newlines. If text has ≤ n lines, copy all of it. Return bytes written, or -1 on NULL/overflow/n<0.

Hints

  1. Count total lines (newlines, plus a partial last line).
  2. Find the start offset of the (total-n)-th line.
  3. Copy from there to the end.

Why this matters

tail -n is a daily tool; reproducing it means finding the right starting offset by counting newlines from the end.

Starter code

#include <stddef.h>
int tail_lines(const char *text, int n, char *out, size_t cap) {
    /* TODO */
    (void)text; (void)n; (void)out; (void)cap;
    return -1;
}

Common mistakes

Off-by-one when the text doesn't end in a newline. Not bounding the copy by cap.

Edge cases to handle

n larger than the line count → whole text. n=1 → just the last line.

Complexity

O(text length).

Background lessons

Up next

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