调用 std::filesystem::status() 前必须先用 exists() 或 is_regular_file() 检查路径存在,否则抛 filesystem_error;它不返回错误码,非幂等且性能开销大,应优先用 directory_entry 缓存状态。

用 std::filesystem::status() 获取文件属性前先确认路径存在
直接调用 std::filesystem::status() 对一个不存在的路径会抛出 std::filesystem::filesystem_error,而不是返回“无效状态”。很多新手误以为它像 stat() 那样返回错误码,结果程序崩溃。
- 务必先用
std::filesystem::exists(path)或std::filesystem::is_regular_file(path)做前置判断 - 若需统一处理(含符号链接目标),改用
std::filesystem::symlink_status(),它不跟随链接,能区分链接本身和目标 - Windows 下注意:NTFS 硬链接、重解析点可能让
status()返回意外的file_type::reparse_file,需额外检查status().type() == file_type::regular
last_write_time() 返回的是 duration,不是时间戳整数
std::filesystem::last_write_time(path) 返回类型是 file_time_type(通常为 std::chrono::time_point),不能直接 printf 或存为 time_t。强行强转或忽略精度会导致时间偏移(常见偏移 1 秒或数小时)。
- 转为 Unix 时间戳(秒级):用
auto t = last_write_time(p); auto s = t.time_since_epoch().count();—— 但注意这是纳秒/100纳秒计数,需除以对应周期(如 Windows 是 100ns,Linux 通常是纳秒) - 更安全的做法是通过
std::chrono::file_clock转换(C++20 起支持):std::chrono::system_clock::from_time_t(std::chrono::file_clock::to_time_t(t)) - 跨平台项目慎用
to_time_t():MSVC 和 libstdc++ 实现有差异,Clang/libc++ 在某些版本中尚未完全支持file_clock::to_time_t
权限位在不同系统上含义不同,status().permissions() 不是 chmod 位图直译
std::filesystem::perms 枚举值(如 owner_read)映射到实际 OS 权限时,Windows 和 POSIX 行为不一致。例如 Windows 没有“组执行”概念,但 perms::group_exec 仍可能被设为 true(来自 ACL 解析结果)。
- 不要用
static_cast<int>(status().permissions())</int>去比对0644这类八进制值 —— 它在 Windows 上无意义 - 检查读写权限建议用语义化方式:
(st.permissions() & perms::owner_read) == perms::owner_read - Windows 下若文件受 ACL 控制,
status()可能无法反映真实访问能力(比如用户有 deny 权限),此时需调用 Win32 APIGetEffectiveRightsFromAcl
性能敏感场景慎用多次 status() 调用
每次 std::filesystem::status() 都触发一次系统调用(stat() 或 GetFileAttributesEx)。循环中反复查同一文件的大小+时间+权限,会显著拖慢 I/O 密集型任务。
立即学习“C++免费学习笔记(深入)”;
- 一次性获取全部信息:用
std::filesystem::directory_entry(构造时缓存状态),再调用entry.status()、entry.file_size()、entry.last_write_time() - 遍历目录时优先用
std::filesystem::recursive_directory_iterator,它内部已预取directory_entry,避免重复 stat - 注意:
directory_entry::status()可能抛异常,仍需 try/catch;且其缓存不自动刷新,路径内容变更后需重新构造 entry
status() 当成纯函数来用——它既不幂等,也不轻量,还高度依赖底层实现细节。尤其是混合使用符号链接、网络驱动器、OneDrive 同步目录时,file_time_type 的精度丢失和权限判定失效几乎必然出现。


















