一、题目要求
编写一个C语言程序,实现文件的复制功能。用户可以输入源文件和目标文件的路径,程序将源文件的内容复制到目标文件中。
请根据要求在begin/end间完成代码,不要改变代码中的其他部分。
二、程序代码
#include <stdio.h>
#define BUFFER_SIZE 1024
int main() {
FILE *sourceFile, *targetFile;
char sourcePath[100], targetPath[100];
char buffer[BUFFER_SIZE];
size_t bytesRead;
// 输入源文件和目标文件路径
printf("Enter source file path: \n");
scanf("%s", sourcePath);
printf("Enter target file path: \n");
scanf("%s", targetPath);
// 打开源文件和目标文件
sourceFile = fopen(sourcePath, "rb");
if (sourceFile == NULL) {
printf("Failed to open source file.\n");
return 1;
}
targetFile = fopen(targetPath, "wb");
if (targetFile == NULL) {
printf("Failed to create target file.\n");
fclose(sourceFile);
return 1;
}
// 复制文件内容
while ((bytesRead = fread(buffer, 1, BUFFER_SIZE, sourceFile)) > 0) {
///Begin///
fwrite(buffer,1, sizeof(buffer), targetFile);//将buffer数组中的内容写入二进制文件 targetFile
End
}
// 关闭文件
fclose(sourceFile);
fclose(targetFile);
printf("File copied successfully.\n");
return 0;
}