linux-sysprog · beginner · ~20 min
Compute the right slice offset; bound-check the copy.
Implement size_t tail_bytes(const char *buf, size_t n, char *out, size_t cap, size_t want) that copies the last want bytes of buf (or all of buf if want > n) into out (capped at cap - 1, NUL-terminated). Returns the number of bytes copied.
tail is fundamental to log viewing. The byte-mode kernel is just 'last N bytes' — and 'last N lines' is built on top of it.
buf/n source; out/cap destination; want bytes.
Bytes copied; out NUL-terminated.
No allocations.
#include <stddef.h>
size_t tail_bytes(const char *buf, size_t n, char *out, size_t cap, size_t want) { /* TODO */ return 0; }
Computing start = n - want when want > n → underflow on size_t; not reserving the NUL byte in cap.
want == 0 → out is empty string. want > n → copy entire buf. cap == 1 → only NUL fits.
O(want).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.