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...
");
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;
}
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP