Copying files - C++ File Stream

C++ examples for File Stream:File Operation

Description

Copying files

Demo Code

#include  <iostream>                                  // For standard  streams
#include  <cctype>                                    // For character functions
#include  <fstream>
#include  <string>
#include  <stdexcept>                                 // For standard exceptions
using  std::string;
using  std::ios;//from  w  ww . j a  v a  2s.c o  m

void validate_files(string source, string target);    // Validate the files

int  main(int argc, char*  argv[]) {
    try
    {
      const string source {"source"};                      // The input file
      const string target {"target"};                      // The destination for the copy

      validate_files(source, target);

      // Create file streams
      std::ifstream in {source, ios::in | ios::binary};
      std::ofstream out(target, ios::out | ios::binary | ios::trunc);

      // Copy  the  file
      char ch {};
      while (in.get(ch))
        out.put(ch);

      if (in.eof())
        std::cout << source << " copied to  " << target << " successfully." << std::endl;
      else
        std::cout << "Error copying file" << std::endl;
    }
    catch (std::exception& ex)
    {
      std::cout << std::endl << typeid(ex).name() << ": " << ex.what();
      return 1;
    }
}

void validate_files(string infile, string outfile){
  std::ifstream in {infile, ios::in | ios::binary};
  if (!in)                                            // Stream object
    throw ios::failure {string("Input file ") + infile + " not found"};

  std::ifstream temp {outfile, ios::in | ios::binary};
  if (temp)
  {
    temp.close();                                     // Close the stream
    std::cout << outfile << " exists, do you want to  overwrite it? (y or n): ";

    if (std::toupper(std::cin.get()) != 'Y'){
      std::cout << "Destination file contents to be kept. Terminating..." << std::endl;
    }
  }
}

Result


Related Tutorials