Open In App

C++ Program to Read Content From One File and Write it Into Another File

Last Updated : 04 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Create an input file stream object and open file.txt in it.
  2. Create an output file stream object and open file2.txt in it.
  3. 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++




// C++ program to read contents from
// one file and write it to another file
#include<bits/stdc++.h>
using namespace std;
  
// Driver code
int main()
{  
  // Input file stream object to 
  // read from file.txt
  ifstream in("file1.txt");
    
  // Output file stream object to 
  // write to file2.txt
  ofstream f("file2.txt");
      
  // Reading file.txt completely using 
  // END OF FILE eof() method
  while(!in.eof())
  {
    // string to extract line from 
    // file.txt
    string text;
        
    // extracting line from file.txt
    getline(in, text);
        
    // Writing the extracted line in 
    // file2.txt
    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. 

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads