Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to merge two files and write into another file

C++ Code Example — File Handling Programs

ADVERTISEMENT

WAP to merge two files and write into another file

Objective

Write a C++ program to merge two files and write the combined output into a third file.

Algorithm / Approach

  1. Create two ifstream objects for the two source files, and one ofstream object for the destination file.
  2. Open the first two files in read mode (ios::in).
  3. Open the destination file in append mode (ios::app).
  4. Run a loop to read every character of file 1 and write it to the destination.
  5. Run a second loop to read every character of file 2 and write it to the destination.
  6. Close all three files.
main.cpp
#include<iostream>
#include<fstream>
using namespace std;
class Test {
 public:
 void mergee() {
  char c;
  char f1[20],f2[20],f3[20];
  ifstream in1,in2;
  ofstream out;
  cout<<"Enter 1st File Name: ";
  cin.getline(f1,20);
  cout<<"Enter 2nd File Name: ";
  cin.getline(f2,20);
  in1.open(f1,ios::in);
  in2.open(f2,ios::in);
  if(!in1 || !in2){
   cout<<"File doesn't exists";
   return;
  }
  else {
   cout<<"Enter 3rd File Name: ";
   cin.getline(f3,20);
   out.open(f3,ios::app);
   while(in1.eof()==0) {
    in1.get(c);
    out<< c;
   }
   while(in2.eof()==0){
    in2.get(c);
    out<< c;
   }
   out.close();
   cout<<"File Merged";
  }
  in1.close();
  in2.close();
 }
};
int main() {
 Test t;
 t.mergee();
 return 0;
}

Expected Output

Enter 1st File Name: apps.txt
Enter 2nd File Name: sol.txt
Enter 3rd File Name: me.txt
File Merged

Explanation of the Program

  • This program reads the entirety of the first file and dumps it into the third file, then does the exact same thing for the second file.
  • Notice the use of ios::app (Append mode) when opening the third file. While ios::out wipes a file clean before writing, ios::app safely adds new data to the very end of the file without destroying what is already there.

Complexity

Time Complexity O(n + m) - Where n and m are the sizes of the two source files.
Space Complexity O(1)
ADVERTISEMENT