Skip to content
Related Articles
Open in App
Not now

Related Articles

C++ Program to Copy the Contents of One File Into Another File

Improve Article
Save Article
  • Last Updated : 25 Jul, 2022
Improve Article
Save Article

Here, we will see how to develop a C++ program to copy the contents of one file into another file. Given a text file, extract contents from it and copy the contents into another new file. After this, display the contents of the new file.


  1. Open the first file which contains data. For example, a file named “file1.txt” contains three strings on three separate lines “Programming   Tutorials”, “By Geeks for geeks” and “Happy Coding!”. 
  2. Open the second file to copy the data from the first file.
  3. Extract the contents of the first file line by line and write the same content to the second file named “file2.txt” via while loop.
  4. Extract the contents of the second file and display it via the while loop.


// C++ to demonstrate copying
// the contents of one file
// into another file
#include <bits/stdc++.h>
using namespace std;
int main()
    // filestream variables
    fstream f1;
    fstream f2;
    string ch;
    // opening first file to read the content"file1.txt", ios::in);
    // opening second file to write
    // the content copied from
    // first file"file2.txt", ios::out);
    while (!f1.eof()) {
        // extracting the content of
        // first file line by line
        getline(f1, ch);
        // writing content to second
        // file line by line
        f2 << ch << endl;
    // closing the files
    // opening second file to read the content"file2.txt", ios::in);
    while (!f2.eof()) {
        // extracting the content of
        // second file line by
        // line
        getline(f2, ch);
        // displaying content
        cout << ch << endl;
    // closing file
    return 0;


Programming Tutorials
By Geeks for geeks
Happy Coding!

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!