#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024 * 1024 // 1MB缓冲区大小
void copyFile(const char *srcFileName, const char *destFileName) {
FILE *srcFile, *destFile;
char buffer[BUFFER_SIZE];
size_t bytesRead;
// 打开源文件
srcFile = fopen(srcFileName, "rb");
if (srcFile == NULL) {
perror("无法打开源文件");
return;
}
// 打开目标文件
destFile = fopen(destFileName, "wb");
if (destFile == NULL) {
perror("无法打开目标文件");
fclose(srcFile);
return;
}
// 循环读取源文件并写入目标文件
while ((bytesRead = fread(buffer, 1, BUFFER_SIZE, srcFile)) > 0) {
if (fwrite(buffer, 1, bytesRead, destFile) != bytesRead) {
perror("写入目标文件错误");
fclose(srcFile);
fclose(destFile);
remove(destFileName); // 删除不完整的目标文件
return;
}
}
if (ferror(srcFile)) {
perror("读取源文件错误");
fclose(srcFile);
fclose(destFile);
remove(destFileName); // 删除不完整的目标文件
return;
}
fclose(srcFile);
fclose(destFile);
printf("文件拷贝成功\n");
}
int main() {
const char *srcFileName = "source_file.bin";
const char *destFileName = "destination_file.bin";
copyFile(srcFileName, destFileName);
return 0;
}
文件拷贝性能优化方法
- 增大缓冲区大小:如上述代码中设置了1MB的缓冲区,较大的缓冲区减少了系统调用次数,提高读写效率。但缓冲区过大可能会占用过多内存,需根据系统内存情况调整。
- 使用更高效的I/O函数:例如,在Linux系统下可使用
sendfile
函数,它在内核空间直接进行数据传输,避免了用户空间和内核空间的数据拷贝,大幅提高性能。
- 异步I/O:使用异步I/O函数,如
aio_read
和aio_write
,允许程序在I/O操作进行时执行其他任务,提高整体效率。
- 多线程或多进程:对于多核CPU系统,可通过多线程或多进程并行处理文件不同部分的读写,充分利用CPU资源提升性能。但要注意线程或进程间的同步和资源竞争问题。