将给定的两个文件设为file1。txt和file2。txt。以下是合并的步骤。 1) 打开文件1。txt和file2。txt处于读取模式。 2) 打开文件3。txt处于写入模式。 3) 运行循环,逐个复制file1的字符。txt到文件3。txt。 4) 运行循环,逐个复制文件2的字符。txt到文件3。txt。 5) 关闭所有文件。
null
要成功运行以下程序文件1。txt和fil2。txt必须存在于同一文件夹中。
#include <stdio.h> #include <stdlib.h> int main() { // Open two files to be merged FILE *fp1 = fopen ( "file1.txt" , "r" ); FILE *fp2 = fopen ( "file2.txt" , "r" ); // Open file to store the result FILE *fp3 = fopen ( "file3.txt" , "w" ); char c; if (fp1 == NULL || fp2 == NULL || fp3 == NULL) { puts ( "Could not open files" ); exit (0); } // Copy contents of first file to file3.txt while ((c = fgetc (fp1)) != EOF) fputc (c, fp3); // Copy contents of second file to file3.txt while ((c = fgetc (fp2)) != EOF) fputc (c, fp3); printf ( "Merged file1.txt and file2.txt into file3.txt" ); fclose (fp1); fclose (fp2); fclose (fp3); return 0; } |
输出:
Merged file1.txt and file2.txt into file3.txt
相关文章:
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END