linux-sysprog · intermediate · ~15 min

Copy bytes between fds

Loop the read/write pair correctly; handle short writes.

Challenge

Copy all bytes from one file descriptor to another until end of input, handling short writes.

Task

Implement ssize_t fd_copy(int src, int dst) that reads from src and writes to dst until src reaches EOF, returning the total number of bytes copied. No main — the grader calls it.

Input

  • src: a readable file descriptor.
  • dst: a writable file descriptor.

Output

The total bytes copied as an ssize_t, or -1 on a read/write error.

Example

src holds "this is fd_copy" (15 bytes)
  ->   fd_copy(src, dst) returns 15; dst receives the same bytes

Edge cases

  • Empty input copies 0 bytes and returns 0.
  • write may transfer fewer bytes than requested; loop until the whole chunk is written.

Rules

  • Use a fixed buffer (e.g. 4096 bytes) and loop read/write; treat a read of 0 as EOF.

Input format

Two file descriptors: src (readable) and dst (writable).

Output format

Total bytes copied as an ssize_t, or -1 on error.

Constraints

Loop read/write with a fixed buffer; handle short writes; read of 0 is EOF.

Starter code

#include <unistd.h>
#include <stddef.h>

ssize_t fd_copy(int src, int dst) {
    /* TODO */
    return -1;
}

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