file-handling · intermediate · ~12 min

Copy a file in chunks

Stream-copy through a bounded buffer with correct short-read/write handling.

Challenge

Your job

int copy_file(const char *src, const char *dst);

Copy src to dst using a fixed-size buffer (chunked fread/fwrite). Return 0 on success, -1 if either file can't be opened or a write is short.

Hints

  1. Open src "rb", dst "wb".
  2. Loop: fread a chunk, fwrite exactly that many; stop at EOF.
  3. Close both on every exit path.

Why this matters

Streaming a file through a fixed buffer — instead of loading it all into memory — is the pattern behind cp, backups, and uploads.

Starter code

#include <stdio.h>
int copy_file(const char *src, const char *dst) {
    /* TODO */
    (void)src; (void)dst;
    return -1;
}

Common mistakes

Writing sizeof(buf) instead of the bytes actually read. Leaking the src handle when dst fails to open.

Edge cases to handle

Multi-chunk file (>4 KiB). Missing source. NULL args.

Complexity

O(filesize).

Background lessons

Up next

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