卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章21413本站已运行3415

C程序将一个文件的内容复制到另一个文件中

C程序将一个文件的内容复制到另一个文件中

C文件I/O − 创建、打开、读取、写入和关闭文件

C文件管理

文件可用于存储大量持久数据。像许多其他语言一样,'C'提供以下文件管理函数:

  • 创建文件
  • 打开文件
  • 读取文件
  • 向文件写入
  • 关闭文件

以下是'C'中最重要的文件管理函数:

函数目的
fopen ()创建文件或打开现有文件
fclose ()关闭文件
fprintf ()向文件写入数据块
fscanf ()从文件中读取数据块
getc ()从文件中读取单个字符
putc ()向文件中写入单个字符
getw ()从文件中读取整数
putw ()向文件中写入整数
fseek ()将文件指针位置设置为指定位置
ftell ()返回文件指针的当前位置
rewind ()将文件指针设置为文件开头

Input:
sourcefile = x1.txt
targefile = x2.txt
Output: File copied successfully.

说明

在这个程序中,我们将一个文件复制到另一个文件,首先您将指定要复制的文件。我们将打开文件,然后以“读”模式读取要复制的文件,以“写”模式读取目标文件。

示例

#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
   char ch;// source_file[20], target_file[20];
   FILE *source, *target;
   char source_file[]="x1.txt";
   char target_file[]="x2.txt";
   source = fopen(source_file, "r");
   if (source == NULL) {
      printf("Press any key to exit...</p><p>");
      exit(EXIT_FAILURE);
   }
   target = fopen(target_file, "w");
   if (target == NULL) {
      fclose(source);
      printf("Press any key to exit...</p><p>");
      exit(EXIT_FAILURE);
   }
   while ((ch = fgetc(source)) != EOF)
      fputc(ch, target);
   printf("File copied successfully.</p><p>");
   fclose(source);
   fclose(target);
   return 0;
}
卓越飞翔博客
上一篇: 三角形火柴棍数的C/C++程序?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏