Here, we will see how to read contents from one file and write it to another file using a C++ program. Let us consider two files file1.txt and file2.txt. We are going to read the content of file.txt and write it in file2.txt
Contents of file1.txt:
Welcome to GeeksForGeeks
Approach:
- Create an input file stream object and open file.txt in it.
- Create an output file stream object and open file2.txt in it.
- Read each line from the file and write it in file2.
Below is the C++ program to read contents from one file and write it to another file:
C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
ifstream in( "file1.txt" );
ofstream f( "file2.txt" );
while (!in.eof())
{
string text;
getline(in, text);
f << text << endl;
}
return 0;
}
|
Output:
file1.txt
GeeksforGeeks is a Computer Science portal for geeks.
file2.txt
GeeksforGeeks is a Computer Science portal for geeks.