jackleberryfin
jackleberryfin

Reputation: 11

std::filesystem::copy throws filesystem_error

Attempting to run this code:

filesystem::copy_options copyOptions = filesystem::copy_options::skip_existing | filesystem::copy_options::recursive | filesystem::copy_options::directories_only;
filesystem::copy(pathA, pathB, copyOptions);

The first attempt is successful and operates exactly as I want and is expected... The second attempt (after the pathB structure has been created) fails with this error:

filesystem error: cannot copy: File exists 
[C:\Users\Smith\Documents\Projects\ProjectA\bin\..\pathA] 
[C:\Users\Smith\Documents\Projects\ProjectA\bin\..\pathB]

The expectation I have is that using skip_existing or overwrite_existing should not throw this error. How does one use this copy method without having to delete pathB each time before use?

Link to cppreference i'm looking at

Upvotes: 1

Views: 4413

Answers (2)

Isaac Wolf
Isaac Wolf

Reputation: 389

I had this exact issue and turns out it occurs when the two paths are completely identical. In my case, the user set the output path, and then configuration files where copied from a source directory. If the user set the output path as the source directory, the command would end up being something like

fs::copy("path/to/config.txt", "path/to/config.txt", fs::copy_options::update_existing);

Which, even with update_existing or overwrite_existing, throws the error

terminate called after throwing an instance of 'std::filesystem::__cxx11::filesystem_error'
  what():  filesystem error: cannot copy: File exist

Upvotes: 1

Bandula Dharmadasa
Bandula Dharmadasa

Reputation: 867

You need to use the flag std::filesystem::copy_options::overwrite_existing.

This solve your problem.

Upvotes: 0

Related Questions