linux-sysprog · beginner · ~15 min
Two-sink fan-out with independent truncation.
Copy one source buffer into two destination buffers at once, like the tee command splitting a stream — each destination truncated to its own capacity.
Implement int tee_to_buffers(const char *src, size_t n, char *out_a, size_t cap_a, char *out_b, size_t cap_b) that copies src into both out_a and out_b.
src, n: the source bytes and their count.out_a, cap_a and out_b, cap_b: the two destinations and their capacities (including room for the NUL).Copies as many of the n bytes as fit into each destination (at most cap - 1 bytes each), NUL-terminating both. Returns the number of bytes that made it into both — that is, min(bytes copied to A, bytes copied to B).
tee_to_buffers("hello", 5, a, 16, b, 16) -> 5, a = "hello", b = "hello"
tee_to_buffers("hello", 5, a, 3, b, 16) -> 2, a = "he", b = "hello"
cap == 1: only the NUL fits, so that side copies 0 bytes.n == 0: both outputs are empty strings, returns 0.cap >= 1).tee is the unsung hero of shell pipelines — it duplicates a stream. Implementing the inner loop teaches the 'short-write' lesson: write() may not write everything you asked.
src/n source bytes, plus two destination buffers out_a/out_b with capacities cap_a/cap_b.
Copies into both (each capped at cap-1, NUL-terminated); returns min(bytes into A, bytes into B).
Each side truncates independently to cap-1. Always NUL-terminate. No allocations.
#include <stddef.h>
int tee_to_buffers(const char *src, size_t n, char *out_a, size_t cap_a, char *out_b, size_t cap_b) { /* TODO */ return 0; }
Returning bytes-written for one buffer but the other was truncated more; forgetting the NUL byte budget.
cap == 1: only NUL fits. n == 0: both outputs are empty.
O(n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.