Introduction
In this lab, we will learn how to copy contents of one file to another using file handling in C++ language.
Include Header Files and Namespaces
In the first step, we will include the necessary header files and namespaces in order to proceed with the code.
#include <iostream>
#include <fstream>
using namespace std;
Copy One File to Another
In this step, we will perform the following actions:
- Create objects of
ifstreamandofstreamclasses. - 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 fromifstreamobject toofstreamobject). - Close files after the copy using the
close()method.
void copyFile(string sourceFile, string destinationFile){
string line;
// creating ifstream and ofstream objects
ifstream sourceFileStream(sourceFile);
ofstream destinationFileStream(destinationFile);
// Reading from source file and writing to destination file
if(sourceFileStream.is_open() && destinationFileStream.is_open()){
while(getline(sourceFileStream, line)){
destinationFileStream << line << "\n";
}
cout<<"Copy Finished"<<endl;
}
else{
printf("Cannot read File");
}
//closing file
sourceFileStream.close();
destinationFileStream.close();
}
Main Function
In this step, we will create a main function to perform the file copy operation by calling our copyFile() function.
int main(){
string sourceFile = "original.txt";
string destinationFile = "copy.txt";
copyFile(sourceFile, destinationFile);
return 0;
}
Compile and Run
In this step,because the code file is saved in ~/project/main.cpp, we can change the current directory to ~/project and run the following commands in terminal:
g++ main.cpp -o main
./main
This will compile and execute the program and produces the output:
Copy Finished
Final Code
#include <iostream>
#include <fstream>
using namespace std;
void copyFile(string sourceFile, string destinationFile){
string line;
// creating ifstream and ofstream objects
ifstream sourceFileStream(sourceFile);
ofstream destinationFileStream(destinationFile);
// Reading from source file and writing to destination file
if(sourceFileStream.is_open() && destinationFileStream.is_open()){
while(getline(sourceFileStream, line)){
destinationFileStream << line << "\n";
}
cout<<"Copy Finished"<<endl;
}
else{
printf("Cannot read File");
}
//closing file
sourceFileStream.close();
destinationFileStream.close();
}
int main(){
string sourceFile = "original.txt";
string destinationFile = "copy.txt";
copyFile(sourceFile, destinationFile);
return 0;
}
Summary
In this lab, an application was created that allows users to copy contents of one file to another file using file handling methods in C++ language.



