C Program to merge two files and store result

In this post, we will write a Program to merge two files and store the output on the third file.

Logic:

  • The files which are to be merged are opened in “read” mode.
  • The file which contains content of both the files is opened in “write” mode.
  • To merge two files first we open a file and read it character by character and store the read contents in the merged file.
  • Then we read the contents of another file and store it in merged file, we read two files until EOF (end of file) is reached.
  • Now we have both the files merged into the third file.

Now let’s write the program for the same.

C Program to merge two files and store the output into another file:

#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;
}

 

 SAMPLE OUTPUT:

merge two files

 

Enter name of first file
date.c
Enter name of seconds file
factorial.c
Enter name of file which will store content of two files
date-factorial.c
Two files were merged into date-factorial.c file successfully.

Comment if you have any issue or concerns.

Leave a Comment