Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to copy content of a file into another file

C++ Code Example — File Handling Programs

ADVERTISEMENT

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

  1. Create an ifstream to read the source file and an ofstream to write to the destination file.
  2. Open both files.
  3. Check if the source file exists.
  4. Loop until in.eof() is reached.
  5. Read a character from the source (in.get(c)) and immediately write it to the destination (out << c).
  6. 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)
ADVERTISEMENT