/*
* Copyright ©2026 Soham Pardeshi. All rights reserved.
* Permission is hereby granted to students registered for University of
* Washington CSE 333 for use solely during Summer Quarter 2026 for
* purposes of the course. No other use, copying, distribution, or
* modification is permitted without prior written consent. Copyrights
* for third-party components of this work must be honored. Instructors
* interested in reusing these course materials should contact the author.
*/
#include <stdio.h> // fopen, fread, fwrite, fprintf, fclose
#include <stdlib.h> // EXIT_FAILURE, EXIT_SUCCESS
#define SIZE 4096 // copy the file 4 KiB at a time
int main(int argc, char** argv) {
if (argc != 3) {
fprintf(stderr, "usage: ./cp_example <src> <dst>\n");
return EXIT_FAILURE;
}
char buf[SIZE];
size_t n;
FILE* fin = fopen(argv[1], "rb");
if (fin == NULL) {
fprintf(stderr, "no input\n");
return EXIT_FAILURE;
}
FILE* fout = fopen(argv[2], "wb");
if (fout == NULL) {
fprintf(stderr, "no output\n");
fclose(fin); // don't leak the stream we already opened
return EXIT_FAILURE;
}
// fread a chunk, then fwrite exactly the n bytes we got.
// Repeat until fread returns 0 (end of file).
while ((n = fread(buf, 1, SIZE, fin)) > 0) {
fwrite(buf, 1, n, fout);
}
// fclose flushes buffered output so the final bytes truly reach disk.
fclose(fin);
fclose(fout);
return EXIT_SUCCESS;
}