std::filesystem::copy throws filesystem_error

std::filesystem::copy throws filesystem_error

本文关键字:filesystem error copy std throws      更新时间:2023-10-16

正在尝试运行此代码:

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

第一次尝试是成功的,完全按照我的意愿和预期进行。。。第二次尝试(在创建pathB结构之后(失败,并出现以下错误:

filesystem error: cannot copy: File exists 
[C:UsersSmithDocumentsProjectsProjectAbin..pathA] 
[C:UsersSmithDocumentsProjectsProjectAbin..pathB]

我的期望是,使用skip_existing或overwrite_existing不应该引发此错误。如何使用这种复制方法而不必每次使用前都删除路径B?

链接到cppreference我正在看

您需要使用标志std::filesystem::copy_options::overwrite_existing

这解决了你的问题。

我遇到了这个确切的问题,结果发现当两条路径完全相同时就会发生。在我的例子中,用户设置输出路径,然后设置从源目录复制的配置文件。如果用户将输出路径设置为源目录,则该命令最终将类似于

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

即使使用update_existingoverwrite_existing,也会抛出错误

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