Append content of one file to another in C++

In this tutorial, we will learn how to append the content of one file to another file in C++.

C++ is a general-purpose object-oriented programming language developed by Bjarne Stroustrup of Bell Labs in 1979. Originally C++ was known as ‘C’ with classes. C++ offers some great features, one of which is DFH(Data File Handling).

append content of one file to another file in C++

Now, in order to append a given file to any other desired file, we have to open the original(source) file in input stream and the other file in which the content has to be copied is opened in output stream.

Append content of one file to another file in C++

Here we are considering the name of the first file is source.txt and the name of the second file is target.txt 

#include<iostream>
#include<fstream>
#include<stdio>
#include<conio>
using namespace std;

int main()
{
  ifstream fs;
  ofstream ft;
  char ch, fname1[20], fname2[20];

  cout<<"Enter source file : ";
  gets(fname1);
  fs.open(fname1);
  if(!fs)
  {
    cout<<"Source file does not exist";
    getch();
    exit(1);
  }

  cout<<"Enter target file name : ";
  gets(fname2);
  ft.open(fname2);
  if(!ft)
  {
    cout<<"Target file does not exist";
    fs.close();
    getch();
    exit(2);
  }

  while(fs.eof()==0)
  {
    fs>>ch;
    ft<<ch;
  }

  cout<<"File copied successfully";

  fs.close();
  ft.close();
  
        return 0;
}

This is how we append content of one file to another file in C++.

In the above given C++ program, we create an object (fs) of ifstream to open the source.txt file in input stream and an object (ft) of ofstream to open the target.txt in output stream. And a character ch is declared to get the input from the source file and append it to the target file character by character. Two character arrays have also been declared to get the names of the source and text file.




 

fs.open(fname1); opens the source.txt file in input buffer and if(!fs) checks whether the source file has been opened properly or not.

ft.open(fname2); opens the target.txt file in input buffer and if(!ft) checks whether the target file has been opened properly or not.

Now, that are files have been opened we only have to copy the contents of the file character by character for this we use a loop which constantly checks whether the end of the file has been reached or not and continues to copy the content from the source.txt to the desired file target.txt.

 

After the content has been copied from one file to another, a message is printed on the screen : “File copied successfully”.

Now we simply close the files using fs.close() and ft.close().

Also read:


Leave a Reply

Your email address will not be published. Required fields are marked *