file-handling · beginner · ~20 min

Final Project: mini-cat — concatenate buffers

Safe bounded copy with a running pointer + remaining-capacity counter.

Challenge

Implement size_t cat_buffers(const char **bufs, const size_t *lens, size_t n, char *out, size_t cap) that concatenates n buffers into out (up to cap bytes including a trailing NUL). Returns the total number of bytes written (not counting NUL). Truncates safely if cap would be exceeded.

Why this matters

cat looks trivial but the careful concatenation with bounds checking is a model for all 'copy bytes into a fixed buffer' patterns — the place where strncpy footguns kill projects.

Input format

Arrays bufs[n], lens[n]; out buffer of cap bytes.

Output format

Bytes written (excluding NUL). out is always NUL-terminated.

Constraints

Cap >= 1. No malloc.

Starter code

#include <stddef.h>
size_t cat_buffers(const char **bufs, const size_t *lens, size_t n, char *out, size_t cap) { /* TODO */ return 0; }

Common mistakes

Forgetting the NUL byte in the budget; using strcat (re-scans every call — O(n^2)); writing one byte past the buffer.

Edge cases to handle

cap == 1 (only the NUL fits). n == 0 (just NUL out). One buffer larger than cap (truncate).

Complexity

O(total bytes).

Background lessons

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