file-handling · intermediate · ~12 min

Copy a file in chunks

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

Challenge

Copy one file to another by streaming it through a small fixed buffer instead of loading it all into memory — the pattern behind cp, backups, and uploads.

Task

Implement int copy_file(const char *src, const char *dst) that copies the contents of src to dst, reading and writing in fixed-size chunks.

Input

  • src: source filename (the grader creates it).
  • dst: destination filename (created/overwritten).

Output

Return 0 on success (every byte of src copied to dst). Return -1 if either file can't be opened, a write comes up short, or an arg is NULL.

Example

src.bin = 5000 bytes
copy_file("src.bin", "dst.bin")   ->   0   (dst.bin is byte-for-byte identical)
copy_file("nope.bin", "dst.bin")  ->   -1  (source missing)

Edge cases

  • Source missing or NULL arg: -1.
  • File larger than one chunk: loop until EOF.
  • Write exactly the number of bytes each read returned, not the whole buffer.

Rules

  • Use a fixed-size buffer (e.g. 4096 bytes); close both handles 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.

Input format

src: file to copy from. dst: file to copy to (overwritten).

Output format

0 on a complete copy; -1 on open failure, short write, or NULL arg.

Constraints

Chunked fread/fwrite through a fixed buffer; write only the bytes read.

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.