linux-sysprog · beginner · ~15 min
Two-sink fan-out with independent truncation.
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 writes the source bytes to both out_a and out_b, truncating each independently. Returns the number of bytes successfully written to both (i.e. the min of the two truncated counts). Always NUL-terminates each output (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; two out buffers with caps.
Min of bytes written; both outputs NUL-terminated.
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.