SOURCE FILE: 04_my_cp.cpp



#include <iostream>
#include<fstream>

using namespace std ;

/*
     This program illustrates using an input file stream with an output file
     stream.

     It is designed to make a new copy of an existing file, and to count the
     number of characters in the file.
*/

int main ()
{
  char fromFileName[256], toFileName[256] ;

  cout << "Please type the name of the 'from' file: " ;
  cin >> fromFileName ;

  cout << "Please type the name of the 'to' file: " ;
  cin >> toFileName ;

  ifstream f_in ;
  f_in.open(fromFileName);
  if (f_in.fail())
  {
    cout << "FAILED TO OPEN INPUT FILE: " << fromFileName << endl ;
    exit(1) ;
  }

  ofstream f_out ;
  f_out.open(toFileName);
  if (f_out.fail())
  {
    cout << "FAILED TO OPEN OUTPUT FILE: " << toFileName << endl ;
    exit(1) ;
  }

  int numCharsCopied = 0 ;

  char next_char ;

  f_in.get(next_char) ; // priming read
  while ( !f_in.eof() )
  {
    f_out.put(next_char) ; // copy the latest character to the ouput file
          // f_out << next_char ; // this would work too
    numCharsCopied++ ; 
    f_in.get(next_char) ;
  }
  
  f_in.close() ;
  f_out.close() ;

  cout << "\n\nCopied " << numCharsCopied << " characters from\n" ;
  cout << "file: " << fromFileName << " to\n" ;
  cout << "file: " << toFileName << endl ;
  cout << "All Done!!\n\n" ;

  return 0 ;
}