File Copy - make backup copies of the files passed to the program - C++ File Stream

C++ examples for File Stream:File Operation

Description

File Copy - make backup copies of the files passed to the program

Demo Code

#include <string>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    for (int n = 1; n < nNumberofArgs; n++){
        string szSource(pszArgs[n]);/*from w  w  w.  j  a v  a  2 s . c  o  m*/
        string szTarget = szSource + ".backup";

        ifstream input(szSource.c_str(),ios_base::in|ios_base::binary);

        ofstream output(szTarget.c_str(),ios_base::out|ios_base::binary|ios_base::trunc);
        if (input.good() && output.good())
        {
            cout << "Backing up " << szSource << "...";
            while(!input.eof() && input.good()){
                char buffer[4096];
                input.read(buffer, 4096);
                output.write(buffer, input.gcount());
            }
            cout << "finished" << endl;
        }
        else
        {
            cerr << "Couldn't copy " << szSource << endl;
        }
    }
    return 0;
}

Related Tutorials