首页 > 文章列表 > C程序将一个文件的内容复制到另一个文件中

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

文件复制 文件内容 C程序
256 2023-09-09

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...

");       exit(EXIT_FAILURE);    }    target = fopen(target_file, "w");    if (target == NULL) {       fclose(source);       printf("Press any key to exit...

");       exit(EXIT_FAILURE);    }    while ((ch = fgetc(source)) != EOF)       fputc(ch, target);    printf("File copied successfully.

");    fclose(source);    fclose(target);    return 0; }