file-handling · intermediate · ~12 min
Stream-copy through a bounded buffer with correct short-read/write handling.
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.
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.
src: source filename (the grader creates it).dst: destination filename (created/overwritten).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.
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)
Streaming a file through a fixed buffer — instead of loading it all into memory — is the pattern behind cp, backups, and uploads.
src: file to copy from. dst: file to copy to (overwritten).
0 on a complete copy; -1 on open failure, short write, or NULL arg.
Chunked fread/fwrite through a fixed buffer; write only the bytes read.
#include <stdio.h>
int copy_file(const char *src, const char *dst) {
/* TODO */
(void)src; (void)dst;
return -1;
}
Writing sizeof(buf) instead of the bytes actually read. Leaking the src handle when dst fails to open.
Multi-chunk file (>4 KiB). Missing source. NULL args.
O(filesize).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.