为何std::filesystem::remove()的error_code在文件不存在时返回‘未知错误’?
问题
我想用std::filesystem::remove()删除文件,文件不存在时给出错误提示,写了如下代码:
std::error_code errorCode; if (!std::filesystem::remove("<some file path>", errorCode)) { std::cout << "Could not delete file because " << errorCode.message(); }
但文件不存在时,输出却是Could not delete file because unknown error,为什么不提示“文件不存在”?
根据cppreference文档,我的理解是:
- 不带
error_code的remove版本,文件不存在时返回false,其他错误抛出异常; - 带
error_code的版本,任何错误都返回false,错误原因存入error_code,且不抛出异常。
现在文件不存在时error_code只显示“未知错误”,反而比不带error_code的版本信息更少,是不是我理解有误?
运行环境:Windows 11,Visual Studio 2022 Version 17.11.2。
解答
这是Visual Studio的std::filesystem实现细节导致的:当文件不存在时,返回的error_code对应的是Windows系统错误码(比如ERROR_FILE_NOT_FOUND),但直接调用message()时,没有自动映射为文件系统相关的友好错误描述,所以显示“未知错误”。
你可以通过手动匹配标准文件系统错误码来实现准确的错误提示,这样既跨平台又能正确识别“文件不存在”的情况:
#include <filesystem> #include <iostream> #include <system_error> namespace fs = std::filesystem; int main() { std::error_code ec; const std::string file_path = "<some file path>"; if (!fs::remove(file_path, ec)) { if (ec == fs::errc::no_such_file_or_directory) { std::cout << "Could not delete file because: 文件不存在\n"; } else { std::cout << "Could not delete file because: " << ec.message() << "\n"; } } return 0; }
如果只针对Windows平台,也可以直接判断系统错误码的值(ERROR_FILE_NOT_FOUND对应值为2),但这种写法不具备跨平台性:
if (ec.value() == 2) { std::cout << "Could not delete file because: 文件不存在\n"; }
你的核心理解没有问题——带error_code的版本确实会存储错误原因,只是VS的实现没有让message()直接输出对应的文件系统错误描述,需要手动匹配标准错误码来获取准确提示。
内容的提问来源于stack exchange,提问作者gris_martin
相关产品推荐
相关产品推荐

