#include <stdio.h>
int main() {
FILE *src = fopen("1.tar.gz", "rb");
FILE *dst = fopen("2.tar.gz", "wb");
if (!src || !dst) { perror("fopen"); return 1; }
int ch;
while ((ch = getc(src)) != EOF) {
putc(ch, dst);
}
fclose(dst);
fclose(src);
return 0;
}
"rb"/"wb":Windows 下文本模式会转换 \n↔\r\n,破坏二进制文件(如压缩包、图片)。跨平台复制必须用二进制模式。int ch 而非 char:EOF 通常为 -1,char 可能是有符号或无符号,若为无符号则永远不等于 EOF 导致死循环。用 int 可正确区分有效字节 0xFF 与 EOF。char buf[4096];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), src)) > 0) {
fwrite(buf, 1, n, dst);
}
或使用 sendfile (Linux)、CopyFile (Windows) 等零拷贝/系统级 API 进一步提速。
#include <stdio.h>
#include <stdlib.h>
int copy_file(const char *src_path, const char *dst_path) {
FILE *src = fopen(src_path, "rb");
if (!src) { perror("open src"); return -1; }
FILE *dst = fopen(dst_path, "wb");
if (!dst) { perror("open dst"); fclose(src); return -1; }
char buf[8192];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), src)) > 0) {
if (fwrite(buf, 1, n, dst) != n) { perror("write"); fclose(src); fclose(dst); return -1; }
}
if (ferror(src)) { perror("read"); fclose(src); fclose(dst); return -1; }
fclose(dst);
fclose(src);
return 0;
}
int main(int argc, char **argv) {
if (argc != 3) { fprintf(stderr, "Usage: %s \n", argv[0]); return 1; }
return copy_file(argv[1], argv[2]);
}
文件复制看似简单,关键在于二进制模式、EOF 正确判断、缓冲块读写与完整错误处理。生产代码请直接使用成熟库函数(std::filesystem::copy C++17、boost::filesystem::copy_file、CopyFileEx 等),避免重复造轮子。