原标题:C语言将两个文件的内容合并到第三个文件中

让给定的两个文件是file1.txt和file2.txt。以下是合并的步骤。 1)在读取模式下打开file1.txt和file2.txt。 2)在写入模式下打开file3.txt。 3)运行循环到file1.txt到file3.txt的逐个复制字符。 4)运行一个循环到file2.txt到file3.txt的逐个复制字符。 5)关闭所有文件。

要成功运行以下程序,file1.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;

将file1.txt和file2.txt合并到file3.txt中 返回搜狐,查看更多

责任编辑:

声明:该文观点仅代表作者本人,搜狐号系信息发布平台,搜狐仅提供信息存储空间服务。