用C程序将一个文件的内容复制到另一个文件?
C文件I/O-创建,打开,读取,写入和关闭文件
C文件管理
文件可用于存储大量持久性数据。与其他许多语言一样,“C”提供了以下文件管理功能,
创建文件
开启档案
读取文件
写入文件
关闭档案
以下是“C”中可用的最重要的文件管理功能,
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...\n"); exit(EXIT_FAILURE); } target = fopen(target_file, "w"); if (target == NULL) { fclose(source); printf("Press any key to exit...\n"); exit(EXIT_FAILURE); } while ((ch = fgetc(source)) != EOF) fputc(ch, target); printf("File copied successfully.\n"); fclose(source); fclose(target); return 0; }