file-handling · intermediate · ~12 min
Locate a suffix of lines and copy it within bounds.
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.
tail -n is a daily tool; reproducing it means finding the right starting offset by counting newlines from the end.
#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;
}
Off-by-one when the text doesn't end in a newline. Not bounding the copy by cap.
n larger than the line count → whole text. n=1 → just the last line.
O(text length).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.