C++ Program to Merge Two Files

C++ program to merge two files is provided on this page.

The aim of this cpp program is to merge the contents of two files into a third file.

The contents of first file will get written to third file and then contents of second file will get written to third file just below the contents of first file.

Here is simple version of that simply complex sentence.

Contents of third file looks like below.

Contents of first file
contents of second file

C++ program merge two files

Here the c++ program to read two text files and merge them into a third text (.txt) file.

Before you copy the code and say bye bye to this page, make sure this program file (.cpp) is in same directory as the two text files and text file names are file1.txt and file2.txt, otherwise it will not work.

If you want to make it work with any two files irrespective of their location, simply use their location (hihi :)) instead of file1.txt and file2.txt.

This was very simple, but may be a beginner would have struggled here so.

/* C++ program to merge contents of two files */

#include <iostream>
#include <stdlib.h>
using namespace std;

int main() 
{ 
   // Open two files to be merging

   FILE *fp1 = fopen("file1.txt", "r"); 
   FILE *fp2 = fopen("file2.txt", "r"); 

   // Open third file to store the merged content

   FILE *fp3 = fopen("file3.txt", "w"); 

   if (fp1 == NULL || fp2 == NULL || fp3 == NULL) 
   { 
         cout << "Could not open files \n";
         exit(0); 
   } 
   
   char ch;

   // Copy contents of file1 to file3.txt 

   while ((ch = fgetc(fp1)) != EOF) 
      fputc(ch, fp3); 


   // Copy contents of file2 to file3.txt 

   while ((ch = fgetc(fp2)) != EOF) 
      fputc(ch, fp3); 

   cout << "Merged file1.txt and file2.txt into file3.txt"; 

   fclose(fp1); 
   fclose(fp2); 
   fclose(fp3); 

   return 0; 
}

Output:

Merged file1.txt and file2.txt into file3.txt

Comments