Signup/Sign In

C++ Program To Merge Two File Into the Third File Using File Handling

In this tutorial, we will be learning how to merge two files into the third file using file handling.

Merge Two File Into the Third File Using File Handling in C++

Before moving to the implementation part, let's first understand the working of the algorithm:

Here, we have to write a C++ Program to Merge Two Files or C Program to merge contents of two files into a third file or Write a C++ Program to Merge Two Files into a Single file or C++ program append the two text files or Merging 2 text files into a 3rd text file in C++ or merging two files into one in c++ and display its contents or Merging Two Files Into One or C program to merge two files or C Program to Merge Two Files Concatenate Lines From Two Text Files Into Output File C program to merge alternate lines from two files or C Program to Append the Content of File at the end of Another.

So in this problem, we have to Merge the two file into an another new file. The program first will ask you to enter the first file name after that ask for entering the second file name than program merge the first file and the second file. We have to enter the both file name with extension cause file always have extension or folder not this is useful when you want to merge two files or in other words, we can say that merge two file. This is not copying one file into the another file in this we have to merge two separate file file1 and file2 into file3 or we can say that we are copying the file1 and file2 in the third file file3.

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
int main()
{
 ifstream ifiles1, ifiles2;
 ofstream ifilet;
 char ch, fname1[20], fname2[20], fname3[30];
 cout<<"Enter first file name (with extension like file1.txt) : ";
 gets(fname1);
 cout<<"Enter second file name (with extension like file2.txt) : ";
 gets(fname2);
 cout<<"Enter Third File name of file : ";
 gets(fname3);
 ifiles1.open(fname1);
 ifiles2.open(fname2);
 if(ifiles1==NULL || ifiles2==NULL)
 {
  perror("Error Message ");
  cout<<"Press any key to exit...\n";
  getch();
  exit(EXIT_FAILURE);
 }
 ifilet.open(fname3);
 if(!ifilet)
 {
  perror("Error Message ");
  cout<<"Press any key to exit...\n";
  getch();
  exit(EXIT_FAILURE);
 }
 while(ifiles1.eof()==0)
 {
  ifiles1>>ch;
  ifilet<<ch;
 }
 while(ifiles2.eof()==0)
 {
  ifiles2>>ch;
  ifilet<<ch;
 }
 cout<<"The two files were merged into "<<fname3<<" file successfully..!!";
 ifiles1.close();
 ifiles2.close();
 ifilet.close();
 getch();
}


Enter first file name (with extension like file1.txt) :example1.txt
Enter second file name (with extension like file1.txt) :example2.txt
Enter Third File name of file :merge,txt
The two file were merged into merge,txt file succesfully..!!

Conclusion

Here, in this tutorial, we have implemented the program to Merge Two File Into the Third File Using File Handling.