Introduction
In this lab, we will learn how to copy contents of one file to another using file handling in C++ language.
In this lab, we will learn how to copy contents of one file to another using file handling in C++ language.
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;
In this step, we will perform the following actions:
ifstream
and ofstream
classes.getline()
method and write the same to the destination using the <<
operator ( i.e. copy each line from ifstream
object to ofstream
object).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();
}
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;
}
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
#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;
}
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.