21xrx.com
2024-05-02 05:57:34 Thursday
登录
文章检索 我的文章 写文章
C程序合并两个文件
2021-07-07 10:08:23 深夜i     --     --
C

C 程序合并两个文件并将它们的内容存储在另一个文件中。 要合并的文件以“读取”模式打开,包含两个文件内容的文件以“写入”模式打开。 对于合并,我们打开一个文件并逐个字符读取它并将读取的内容存储在合并文件中,然后对第二个文件重复此操作。 读取文件直到到达它们的 EOF(文件结尾)。

 

C程序

#include <stdio.h>
#include <stdlib.h>


int main()
{
  FILE *fs1, *fs2, *ft;

  char ch, file1[20], file2[20], file3[20];

  printf("Enter name of first file\n");
  gets(file1);

  printf("Enter name of second file\n");
  gets(file2);

  printf("Enter name of file which will store contents of the two files\n");
  gets(file3);

  fs1 = fopen(file1, "r");
  fs2 = fopen(file2, "r");

  if (fs1 == NULL || fs2 == NULL)
  {
    perror("Error ");
    printf("Press any key to exit...\n");
    exit(EXIT_FAILURE);
  }

  ft = fopen(file3, "w"); // Opening in write mode

  if (ft == NULL)
  {
    perror("Error ");
    printf("Press any key to exit...\n");
    exit(EXIT_FAILURE);
  }

  while ((ch = fgetc(fs1)) != EOF)
    fputc(ch,ft);

  while ((ch = fgetc(fs2)) != EOF)
    fputc(ch,ft);

  printf("The two files were merged into %s file successfully.\n", file3);

  fclose(fs1);
  fclose(fs2);
  fclose(ft);

  return 0;
}

下载合并文件程序。

程序输出:

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复