linux-sysprog · beginner · ~15 min

Write a buffer to two outputs

Two-sink fan-out with independent truncation.

Challenge

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).

Why this matters

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.

Input format

src/n; two out buffers with caps.

Output format

Min of bytes written; both outputs NUL-terminated.

Constraints

No allocations.

Starter code

#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; }

Common mistakes

Returning bytes-written for one buffer but the other was truncated more; forgetting the NUL byte budget.

Edge cases to handle

cap == 1: only NUL fits. n == 0: both outputs are empty.

Complexity

O(n).

Background lessons

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