linux-sysprog · beginner · ~15 min

Write a buffer to two outputs

Two-sink fan-out with independent truncation.

Challenge

Copy one source buffer into two destination buffers at once, like the tee command splitting a stream — each destination truncated to its own capacity.

Task

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.

Input

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

Output

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

Example

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"

Edge cases

  • cap == 1: only the NUL fits, so that side copies 0 bytes.
  • n == 0: both outputs are empty strings, returns 0.

Rules

  • Always NUL-terminate each output (assume each 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 source bytes, plus two destination buffers out_a/out_b with capacities cap_a/cap_b.

Output format

Copies into both (each capped at cap-1, NUL-terminated); returns min(bytes into A, bytes into B).

Constraints

Each side truncates independently to cap-1. Always NUL-terminate. 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.