Danny
Danny

Reputation: 475

How to copy a directory in C++, using std::filesystem::copy?

So, I'm trying to do something that should be simple. I'm using std::filesystem::copy to copy one directory into another, as such:

#include <filesystem>

int main (int argc, char* argv[])
{
    const char* dir1 = "C:\\Users\\me\\folder";
    const char* dir2 = "C:\\Users\\me\\folder_copy";
    std::filesystem::copy(dir1, dir2, std::filesystem::copy_options::update_existing);

    return 0;
}

However, the above crashes for me when folder_copy already exists, with the following error:

Unhandled exception at 0x00007FF932E9A308 in code.exe: Microsoft C++ exception: std::filesystem::filesystem_error at memory location 0x00000012188FF6D0.

Interestingly, the flag std::filesystem::copy_options::overwrite_existing works fine for me. Is update_existing incompatible with std::filesystem::copy? It would be weird if it only worked with std::filesystem::copy_file.

Anyway, if this is by design, how do I copy a directory while only updating out-of-date files?

Upvotes: 0

Views: 1334

Answers (1)

StPiere
StPiere

Reputation: 4243

Try with:

int main (int argc, char* argv[])
{
    namespace fs = std::filesystem;
    const char* dir1 = "C:/Users/me/folder";
    const char* dir2 = "C:/Users/me/folder_copy";

    try {
        fs::copy(dir1, dir2,          
            fs::copy_options::update_existing
            //|fs::copy_options::overwrite_existing
            |fs::copy_options::recursive);
    }
    catch (const fs::filesystem_error& e) {
        cerr << e.what() << endl;
    }

    return 0;
}

Also check that no file in the destination folder is in use while being updated and that you have sufficient write permissions.

Upvotes: 3

Related Questions