You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MSYS2 Clang++使用std::filesystem库复制文件时报错求助

std::filesystem::copy 报错“File exists”但目标文件不存在

环境信息

  • 系统:Windows 11
  • 编译器:MSYS2 安装的 clang++ 19.1.4(用g++编译也出现相同问题)
    ~ clang++ --version
    clang version 19.1.4
    Target: x86_64-w64-windows-gnu
    Thread model: posix
    InstalledDir: C:/msys64/mingw64/bin
    
  • 编译命令:clang++ .\test.cpp

代码示例

#include <filesystem>

int main(){
    std::filesystem::path p = "C:/Users/Jaden/Documents/hi.txt";
    std::filesystem::path p2 = "C:/Users/Jaden";

    std::filesystem::copy(
        p, p2, std::filesystem::copy_options::overwrite_existing);
}

运行错误

terminate called after throwing an instance of 'std::filesystem::__cxx11::filesystem_error'
  what():  filesystem error: cannot copy: File exists [C:/Users/Jaden/Documents/hi.txt] [C:/Users/Jaden]

问题说明

提前调用std::filesystem::exists检查目标目录下的同名文件,返回结果为false,但无论是否添加copy_options::overwrite_existing标志,都会触发上述报错。

解决方法

问题根源是目标路径指向的是目录而非文件,std::filesystem::copy在源为文件、目标为目录时,需要明确指定目标文件的完整路径,否则会出现路径解析的误判。

修改目标路径的构造方式,直接拼接出完整的目标文件路径:

// 用filesystem的路径拼接,更安全
std::filesystem::path p2 = std::filesystem::path("C:/Users/Jaden") / p.filename();

或者用字符串拼接:

std::filesystem::path p2 = "C:/Users/Jaden/" + p.filename().string();

修改后,std::filesystem::copy能正确识别目标是文件,配合copy_options::overwrite_existing即可正常覆盖(如果文件存在),或者直接创建新文件(如果不存在)。

内容的提问来源于stack exchange,提问作者JadenJin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 16:25:11