Search code examples
c++filecopyreturnportability

How to check if a file copied successfully? (portable solution) C++


How should I modify this code so that it only returns 1 if the file copied successfully?

double file_copy(char *source,char *destination)
{
    std::ifstream srce(source,std::ios::binary);
    std::ofstream dest(destination,std::ios::binary);

    dest << srce.rdbuf();

    srce.close();
    dest.close();

    return ???
}

Thanks!


Solution

  • In C++ prior C++17 the following should be a good solution:

    • .close() is not necessary, since RAII will take care of that
    • correctly and portably handles at least the following cases: missing permissions, missing files, wrong files names, file deleted during write or read, not enough disk space
    • there will be no 0 kb output file in case the input file fails or does not exist

    The code:

    double file_copy(const char *source, const char *destination)
    {
        std::ifstream srce(source,std::ios::binary);
        if(srce.tellg()<0) return 0.0;
    
        std::ofstream dest(destination,std::ios::binary);
        if(dest.tellp()<0) return 0.0;
    
        dest << srce.rdbuf();
        if(srce.tellg()-dest.tellp() != 0) return 0.0;
    
        return 1.0;
    }