To copy the text/contents of one file to another file, we should know the basics of reading and writing a text file in C++. To copy the file using C++, we read the contents of the source file and write it into the destination file.
Steps to copy one file to another in C++:
- Create objects of ifstream and ofstream classes.
- Check if they are connected to their respective files. If so, go ahead otherwise check the filenames twice.
- Read the contents of the source file using the getline() method and write the same to the destination using the << operator ( i.e. copy each line from ifstream object to ofstream object).
- Close files after the copy using the close() method.
- End the program.
Note: ifstream and ofstream classes are present in the <fstream> library.
Example:
C++
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string line;
ifstream ini_file{
"original.txt"
};
ofstream out_file{ "copy.txt" };
if (ini_file && out_file) {
while (getline(ini_file, line)) {
out_file << line << "\n" ;
}
cout << "Copy Finished \n" ;
}
else {
printf ( "Cannot read File" );
}
ini_file.close();
out_file.close();
return 0;
}
|
Output:
Original File – original.txt:

File: original.txt
Copy program running:
Copy File – copy.txt:

Copied file: copy.txt
In this example, we have assumed that both the original file and the copy file are in the same directory where the code file of this program is. The above program runs unless the whole contents of the original file get copied to another file.