C++ Program to Copy the Contents of One File Into Another File
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.
Approach:
- Open the first file which contains data. For example, a file named “file1.txt” contains three strings on three separate lines “Programming Tutorials”, “By Beginner for Beginner” and “Happy Coding!”.
- Open the second file to copy the data from the first file.
- 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.
- Extract the contents of the second file and display it via the while loop.
C++
// 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 f1.open( "file1.txt" , ios::in); // opening second file to write // the content copied from // first file f2.open( "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 f1.close(); f2.close(); // opening second file to read the content f2.open( "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 f2.close(); return 0; } |
Output:
Programming Tutorials By Beginner for Beginner Happy Coding!