C++ provides file-stream classes to read data from one file and write it to another file. The ifstream class is used to read the source file, while ofstream is used to write to the destination file.
- ifstream opens the source file for reading.
- ofstream creates or opens the destination file for writing.
Example:
Suppose file1.txt contains: Welcome to GeeksforGeeks
After running the program, the same content will be written to file2.txt.
Read and Write File Contents Using File Streams
The ifstream and ofstream classes from the <fstream> header can be used to transfer the contents of one file to another.
Approach
- Open the source file using ifstream.
- Open the destination file using ofstream.
- Read the source file line by line using getline().
- Write each line to the destination file.
- Close both files.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Open the source file for reading
ifstream input("file1.txt");
// Open the destination file for writing
ofstream output("file2.txt");
// Check if both files were opened successfully
if (!input || !output) {
cout << "Unable to open file";
return 1;
}
string line;
// Read the source file line by line
while (getline(input, line)) {
// Write each line to the destination file
output << line << endl;
}
// Close both file streams
input.close();
output.close();
return 0;
}
Output
file1.txt
GeeksforGeeks is a Computer Science portal for geeks. file2.txt
GeeksforGeeks is a Computer Science portal for geeks. Explanation
- ifstream opens file1.txt for reading, while ofstream opens file2.txt for writing.
- getline() reads the source file line by line.
- Each line is written to file2.txt using the << operator.
- close() closes both file streams after the operation is completed.
Note: Using while (!input.eof()) is avoided because eof() becomes true only after an attempted read goes