为何GCC会抛出filesystem_error提示无法复制文件?
问题:C++17 filesystem库copy操作在Windows下无法覆盖现有文件
我正在开发一个可读写/复制文件的应用,计划将代码升级至C++17的filesystem库。
运行环境
- Windows 11
- g++ v12.2(MSYS2 MinGW 64-bit)
示例代码
#include <cstdlib> #include <iostream> #include <fstream> #include <filesystem> namespace fs = std::filesystem; int main() { fs::create_directories("sandbox"); std::ofstream ofs; ofs.open ("sandbox/file1.txt", std::ofstream::out | std::ofstream::app); ofs << "hello"; ofs.close(); std::cout << "test copy file" << std::endl; fs::copy("sandbox/file1.txt", "sandbox/file2.txt", fs::copy_options::overwrite_existing); // copy file static_cast<void>(std::system("tree")); // 一段时间后,文件被更新 ofs.open ("sandbox/file1.txt", std::ofstream::out | std::ofstream::app); ofs << "world"; ofs.close(); // 一段时间后,需要通过复制更新file2 std::cout << "test copy file again" << std::endl; fs::copy("sandbox/file1.txt", "sandbox/file2.txt", fs::copy_options::overwrite_existing); // copy file fs::remove_all("sandbox"); }
编译命令
g++ -c -std=gnu++17 testcopy.cpp -o testcopy.o g++ ./testcopy.o -o testcopy.exe
运行结果
./testcopy.exe test copy file Folder PATH listing for volume Acer Volume serial number is 38B3-48F3 C:. └───sandbox test copy file again terminate called after throwing an instance of 'std::filesystem::__cxx11::filesystem_error' what(): filesystem error: cannot copy: File exists [sandbox/file1.txt] [sandbox/file2.txt]
疑问
- 是否需要在第一次复制后对file2.txt执行release、free或close操作?但不知道具体怎么做。
- 会不会是copy_options在Windows下的GCC中不支持?如果是这样,我可能会暂缓将代码移植到C++17。
- 原本以为copy_options::overwrite_existing可以解决“File exists”的问题,也尝试过copy_options::update_existing,但都无效。
内容的提问来源于stack exchange,提问作者Mj Mendoza IV
相关产品推荐
相关产品推荐

