【问题标题】:std::filesystem::copy throws filesystem_errorstd::filesystem::copy 抛出 filesystem_error
【发布时间】:2020-07-11 14:37:39
【问题描述】:

正在尝试运行此代码:

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:\Users\Smith\Documents\Projects\ProjectA\bin\..\pathA] 
[C:\Users\Smith\Documents\Projects\ProjectA\bin\..\pathB]

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

Link to cppreference i'm looking at

【问题讨论】:

    标签: c++ exception copy filesystems c++17


    【解决方案1】:

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

    这解决了你的问题。

    【讨论】:

    • 感谢您的回复,不幸的是我已经尝试过这个并得到相同的结果。我也在问题的底部提到了这一点。
    • 我在我的机器上实现了这个并按预期工作。您的 C++ 安装可能有问题。
    • 您在实施过程中是否以任何方式捕获异常?我正在使用一个非常基本的配置(g++ -std=c++17)。您是否运行了两次副本?
    • 我使用 Visual Studio 2019 和 -std=C++17。我没有使用任何特殊的异常处理代码,而且很简单。甚至,根据文档,它应该是正确的。
    • 你用的是哪个版本的g++?
    【解决方案2】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 2019-05-29
      相关资源
      最近更新 更多