C++ program to append content of one text file to another

Given source and destination text files. Append the content from source file to destination file and then display the content of destination file.

Example :

Input : file.txt : "geeks", file2.txt : "geeks for"
Output: file2.txt : "geeks for geeks"

1) Open file.txt in inputstream and file2.txt in outputstream with append option, so that the previous content of file are not deleted.
2) Check if there’s an error in opening or locating a file. If yes, then throw an error message.
3) If both the files are found, then write content from source file to destination file.
4) Display the content of destination file.





// C++ implementation to append
// content from source file to
// destination file
#include <bits/stdc++.h>
using namespace std;
// driver code
int main()
    fstream file;
    // Input stream class to
    // operate on files.
    ifstream ifile("file.txt", ios::in);
    // Output stream class to
    // operate on files.
    ofstream ofile("file2.txt", ios::out | ios::app);
    // check if file exists
    if (!ifile.is_open()) {
        // file not found (i.e, not opened).
        // Print an error message.
        cout << "file not found";
    else {
        // then add more lines to
        // the file if need be
        ofile << ifile.rdbuf();
    string word;
    // opening file
    // extracting words form the file
    while (file >> word) {
        // displaying content of
        // destination file
        cout << word << " ";
    return 0;



geeks for geeks

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.