C语言程序:将一个文件的内容复制到另一个文件
文件是记录的集合(或)是硬盘上永久存储数据的地方。 使用C命令,我们可以通过不同的方式访问文件。
文件操作
在C语言中,可以对文件执行的操作如下:
- 命名文件。
- 打开文件。
- 从文件中读取。
- 写入文件。
- 关闭文件。
语法
**打开和命名文件**的语法如下:
FILE *File pointer;
例如,FILE * fptr;
File pointer = fopen ("File name”, "mode”);例如,fptr = fopen ("sample.txt”, "r”);
FILE *fp;
fp = fopen ("sample.txt”, "w”);**从文件中读取**的语法如下:
int fgetc( FILE * fp );// read a single character from a file
**写入文件**的语法如下:
int fputc( int c, FILE *fp ); // write individual characters to a stream
借助这些函数,我们可以将一个文件的内容复制到另一个文件。
示例
以下是将一个文件的内容复制到另一个文件的C程序:
#include <stdio.h>
#include <stdlib.h> // For exit()
int main(){
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading
");
scanf("%s",filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL){
printf("Cannot open file %s
", filename);
exit(0);
}
printf("Enter the filename to open for writing
");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL){
printf("Cannot open file %s
", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF){
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("
Contents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;
}输出
执行上述程序后,将产生以下结果:
Enter the filename to open for reading file3.txt Enter the filename to open for writing file1.txt Contents copied to file1.txt
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP