WAP to copy content of a file into another file
Objective
Write a C++ program to copy the contents of one file into another file.
Algorithm / Approach
- Create an
ifstreamto read the source file and anofstreamto write to the destination file. - Open both files.
- Check if the source file exists.
- Loop until
in.eof()is reached. - Read a character from the source (
in.get(c)) and immediately write it to the destination (out << c). - Close both file streams.
main.cpp
#include<iostream>
#include<fstream>
using namespace std;
class Test {
public:
void copy() {
char c;
char f1[10],f2[10];
ifstream in;
ofstream out;
cout<<"Enter File Name to Read: ";
cin.getline(f1,10);
cout<<"Enter File Name to Write: ";
cin.getline(f2,10);
in.open(f1,ios::in);
out.open(f2,ios::out);
if(!in){
cout<<"File doesn't exists";
}
else {
while(in.eof()==0) {
in.get(c);
out<< c;
}
cout<<"File Copied";
}
in.close();
out.close();
}
};
int main() {
Test t;
t.copy();
return 0;
}
Expected Output
Enter File Name to Read: apps.txt Enter File Name to Write: alok.txt File Copied.
Explanation of the Program
- Copying a file is just a combination of the Read and Write programs.
- Instead of reading from a file and printing to the screen (
cout), we read from a file and print directly into a second file (out).
Complexity
Time Complexity
O(n) - Proportional to the size of the source file.
Space Complexity
O(1)