file-handling · intermediate · ~12 min
Stream-copy through a bounded buffer with correct short-read/write handling.
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.
src "rb", dst "wb".fread a chunk, fwrite exactly that many; stop at EOF.Streaming a file through a fixed buffer — instead of loading it all into memory — is the pattern behind cp, backups, and uploads.
#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.