如何检测只读文件是否存在?解决std::filesystem::exists失效问题
解决方案:检测只读系统文件的存在性
你的代码返回“不存在”主要有两个核心问题,逐个解决:
1. 路径转义错误
C++字符串里的反斜杠\是转义字符,你写的"C:\Windows\System32\hal.dll"会被解析成无效路径(比如\W会被当作未定义的转义序列)。修正方式二选一:
- 使用双反斜杠:
"C:\\Windows\\System32\\hal.dll" - 使用C++11及以上的原始字符串字面量:
R"(C:\Windows\System32\hal.dll)"
2. Windows文件系统重定向问题
如果你的程序是32位程序,在64位Windows系统中,访问C:\Windows\System32会被系统自动重定向到C:\Windows\SysWOW64,而hal.dll是64位专属系统文件,仅存在于System32目录,因此检测会失败。
解决重定向问题有两种可行方式:
方式一:临时禁用文件系统重定向
通过Windows API关闭重定向,检测完成后恢复:
#include <windows.h> #include <filesystem> #include <iostream> namespace fs = std::filesystem; int main() { PVOID oldRedirectState = nullptr; // 禁用重定向 if (Wow64DisableWow64FsRedirection(&oldRedirectState)) { if (fs::exists(R"(C:\Windows\System32\hal.dll)")) { std::cout << "Exists" << std::endl; } else { std::cout << "Does not exist" << std::endl; } // 恢复重定向 Wow64RevertWow64FsRedirection(oldRedirectState); } else { std::cout << "Failed to disable filesystem redirection" << std::endl; } return 0; }
方式二:使用Sysnative别名访问64位目录
Windows为32位程序提供了C:\Windows\Sysnative别名,通过它可以直接访问64位的System32目录,无需修改重定向设置:
#include <filesystem> #include <iostream> namespace fs = std::filesystem; int main() { if (fs::exists(R"(C:\Windows\Sysnative\hal.dll)")) { std::cout << "Exists" << std::endl; } else { std::cout << "Does not exist" << std::endl; } return 0; }
补充说明
std::filesystem::exists本身不需要打开文件,它通过查询文件系统元数据判断存在性,完全符合你“无需打开文件”的需求。- 普通用户权限即可检测
hal.dll的存在性,无需管理员权限。
内容的提问来源于stack exchange,提问作者johnrollins
相关产品推荐
相关产品推荐

