用c语言编写程序实现文件的复制功能
时间: 2024-02-10 16:10:49 浏览: 28
可以使用C语言中的文件操作函数来实现文件的复制功能。以下是一个简单的实现示例:
```c
#include <stdio.h>
int main() {
FILE *source_file, *target_file;
char source_file_name[50], target_file_name[50], ch;
printf("请输入源文件名:");
scanf("%s", source_file_name);
printf("请输入目标文件名:");
scanf("%s", target_file_name);
source_file = fopen(source_file_name, "r");
if (source_file == NULL) {
printf("无法打开源文件!\n");
return 0;
}
target_file = fopen(target_file_name, "w");
if (target_file == NULL) {
printf("无法创建目标文件!\n");
fclose(source_file);
return 0;
}
while ((ch = fgetc(source_file)) != EOF) {
fputc(ch, target_file);
}
printf("文件复制完成!\n");
fclose(source_file);
fclose(target_file);
return 0;
}
```
在程序中,首先使用 `fopen` 函数打开源文件和目标文件,如果打开失败则输出错误信息并退出程序。然后在一个循环中,逐个读取源文件中的字符,并将其写入目标文件中。最后关闭文件句柄,释放资源。