C++ Program to Copy the Contents of One File Into Another File
Last Updated :
25 Jul, 2022
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 Geeks for geeks” 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++
#include <bits/stdc++.h>
using namespace std;
int main()
{
fstream f1;
fstream f2;
string ch;
f1.open( "file1.txt" , ios::in);
f2.open( "file2.txt" , ios::out);
while (!f1.eof()) {
getline(f1, ch);
f2 << ch << endl;
}
f1.close();
f2.close();
f2.open( "file2.txt" , ios::in);
while (!f2.eof()) {
getline(f2, ch);
cout << ch << endl;
}
f2.close();
return 0;
}
|
Output:
Programming Tutorials
By Geeks for geeks
Happy Coding!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...