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输出结果#include //Forexit() int main(){ FILE *fptr1, *fptr2; char filename[100], c; printf("Enter the filename to open for reading \n"); scanf("%s",filename); //Openonefileforreading fptr1 = fopen(filename, "r"); if (fptr1 == NULL){ printf("Cannot open file %s \n", filename); exit(0); } printf("Enter the filename to open for writing \n"); scanf("%s", filename); //Openanotherfileforwriting fptr2 = fopen(filename, "w"); if (fptr2 == NULL){ printf("Cannot open file %s \n", filename); exit(0); } //Readcontentsfromfile c = fgetc(fptr1); while (c != EOF){ fputc(c, fptr2); c = fgetc(fptr1); } printf("\nContents 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
热门推荐
10 香港老妈结婚祝福语简短
11 毕业立体贺卡祝福语简短
12 简短新年年会祝福语
13 评论小品祝福语大全简短
14 恭喜师兄结婚祝福语简短
15 员工集体辞职祝福语简短
16 高中新生祝福语 简短
17 装修祝福语男生搞笑简短
18 生日开业蛋糕祝福语简短