Copying one file into another in C++ involves reading the contents of a source file and writing them into a destination file using file stream operations. The C++ <fstream> library provides classes that make file copying simple and efficient.
- ifstream is used to read data from the source file.
- ofstream is used to write the copied data to the destination file.
Steps to Copy a File
The process of copying a file typically involves the following steps:
- Create an ifstream object for the source file.
- Create an ofstream object for the destination file.
- Verify that both files are opened successfully.
- Read the source file line by line using getline().
- Write each line to the destination file.
- Close both files after the copy operation completes.
Note: The ifstream and ofstream classes are defined in the <fstream> header file.
Program to Copy One File into Another
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
string line;
// For writing text file
// Creating ofstream & ifstream class object
ifstream ini_file{
"original.txt"
}; // This is the original file
ofstream out_file{ "copy.txt" };
if (ini_file && out_file) {
while (getline(ini_file, line)) {
out_file << line << "\n";
}
cout << "Copy Finished \n";
}
else {
// Something went wrong
printf("Cannot read File");
}
// Closing file
ini_file.close();
out_file.close();
return 0;
}
Output
Original File – original.txt:

Copy program running:

Copy File – copy.txt:

Explanation
- ifstream opens the source file and ofstream creates the destination file.
- getline() reads the source file line by line, and each line is written to the destination file using the << operator.
- After the copying process completes, both files are closed.