| 
 | 
 
 
发表于 2024-9-20 12:01:36
|
显示全部楼层
 
 
 
 
 
当然可以,这里是使用C语言实现文件复制功能的代码示例: 
 
- #include <stdio.h>
 
 - #include <stdlib.h>
 
 - #include <string.h>
 
  
- void copy_file(const char *file_path) {
 
 -     // 打开源文件
 
 -     FILE *src_file = fopen(file_path, "r");
 
 -     if (src_file == NULL) {
 
 -         fprintf(stderr, "无法打开文件 %s\n", file_path);
 
 -         return;
 
 -     }
 
  
-     // 创建目标文件名
 
 -     char dest_file_path[256];
 
 -     snprintf(dest_file_path, sizeof(dest_file_path), "%s-副本.txt", file_path);
 
  
-     // 打开目标文件
 
 -     FILE *dest_file = fopen(dest_file_path, "w");
 
 -     if (dest_file == NULL) {
 
 -         fclose(src_file);
 
 -         fprintf(stderr, "无法创建文件 %s\n", dest_file_path);
 
 -         return;
 
 -     }
 
  
-     // 复制文件内容
 
 -     char buffer[1024];
 
 -     size_t n;
 
 -     while ((n = fread(buffer, 1, sizeof(buffer), src_file)) > 0) {
 
 -         fwrite(buffer, 1, n, dest_file);
 
 -     }
 
  
-     // 关闭文件
 
 -     fclose(src_file);
 
 -     fclose(dest_file);
 
  
-     printf("文件复制成功: %s\n", dest_file_path);
 
 - }
 
  
- int main() {
 
 -     char file_path[256];
 
 -     printf("请输入文件名 (文件路径): ");
 
 -     scanf("%255s", file_path);
 
  
-     copy_file(file_path);
 
  
-     return 0;
 
 - }
 
  复制代码 
 
在这个示例中: 
1. `copy_file`函数负责读取源文件内容并复制到目标文件。 
2. `snprintf`用于生成目标文件名,目标文件名是在源文件名后面加上"-副本.txt"后缀。 
3. `fread`和`fwrite`用来读取和写入文件内容。 
 
运行程序时输入文件名(文件路径),程序会创建一个以"-副本.txt"结尾的新文件,并将源文件的内容复制进去。 
 
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |   
 
 
 
 |