Signup/Sign In

C++ Program For Copy One File To Another Using File Handling

In this tutorial, we will be learning how to copy one file to another using file handling.

Steps To Copy One File To Another In C++:

To copy the file using C++, we read the contents of the source file and write it into the destination file.

Before moving to the implementation part, let's first understand the working of the algorithm:

  1. Create objects of ifstream and ofstream classes.
  2. 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).
  3. Close files after the copy using the close() method.
  4. End the program
#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{
    string line;
    //For writing text file
    //Creating ofstream & ifstream class object
    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 {
        //Something went wrong
        printf("Cannot read File");
    }
 
    //Closing file
    ini_file.close();
    out_file.close();
 
    return 0;
}


Welcome to Studytonight

Copy Finished

Conclusion

Here, in this tutorial, we have implemented the C++ program to copy one file to another using file handling.