std::filesystem::file_size()需先用exists()和is_regular_file()校验,否则抛filesystem_error;last_write_time()返回file_time_type,须用clock_cast或to_time_t转换后才能格式化输出。

std::filesystem::file_size() 获取文件大小要先检查存在性和是否为常规文件
直接调用 std::filesystem::file_size() 对不存在的路径、目录或符号链接(未解引用)会抛出 std::filesystem::filesystem_error。这不是设计缺陷,而是明确要求你主动处理边界情况。
常见错误现象:程序崩溃并报错 filesystem error: cannot determine file size,尤其在遍历目录时遇到子目录或权限不足的文件。
- 务必先用
std::filesystem::exists()和std::filesystem::is_regular_file()双重校验 - 如果目标可能是符号链接,且你想获取链接指向的目标文件大小,需传入
std::filesystem::symlink_option::follow - 注意:对空文件返回 0,这是合法值,不能用来判断是否存在
try {
const auto p = std::filesystem::path("data.txt");
if (std::filesystem::exists(p) && std::filesystem::is_regular_file(p)) {
uintmax_t size = std::filesystem::file_size(p);
// size 单位是字节
}
} catch (const std::filesystem::filesystem_error& e) {
// 处理权限拒绝、路径不存在等异常
}
std::filesystem::last_write_time() 返回的是 time_point,不是秒数或字符串
std::filesystem::last_write_time() 返回类型是 std::filesystem::file_time_type,它和 std::chrono::system_clock::time_point 不兼容,不能直接丢给 std::put_time() 或 time_t 转换函数。
常见错误现象:编译失败提示 “no matching function for call to ‘to_time_t’”,或运行时得到远古时间(如 1970 年初)——本质是时钟 epoch 不一致导致的误转换。
Agent 记忆系统 — 五路融合检索 + 双时间线 + 因果链 + Spirit管家 + 记忆回声 + 弹性配置 + Circuit Breaker + GDPR合规 + 192项安全审计修复
立即学习“C++免费学习笔记(深入)”;
- 必须通过
std::filesystem::file_time_type::clock的to_time_t()成员函数转换(C++20 起支持),或借助std::chrono::clock_cast(C++20) - 若需格式化输出,先转
time_t,再用std::gmtime()或std::localtime()转结构体 - 注意:Windows 上该时间精度通常是 100ns,但 FAT32 卷可能只到 2s;ext4 通常支持纳秒级,但实际写入取决于内核和挂载选项
if (std::filesystem::exists(p)) {
auto ft = std::filesystem::last_write_time(p);
auto sct = std::chrono::clock_cast<std::chrono::system_clock>(ft);
std::time_t ctt = sct.time_since_epoch().count() / 1'000'000'000;
auto tm = *std::localtime(&ctt);
std::cout << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << "\n";
}
跨平台时注意 last_write_time() 在 FAT32 和某些网络文件系统上的行为差异
FAT32 卷不存储纳秒级时间戳,last_write_time() 返回值会被向下取整到最接近的 2 秒倍数;而某些 NFS 或 SMB 挂载点可能因服务器配置返回不精确时间,甚至缓存旧值。
使用场景:如果你在做文件变更监控(比如热重载资源),仅靠 last_write_time() 可能漏掉快速连续的两次修改(间隔
- 不要依赖微秒/纳秒级精度做逻辑判断,尤其在嵌入式或旧硬件环境
- 对一致性要求高的场景(如构建系统),建议结合
file_size()+last_write_time()双条件判断,或计算文件哈希 - Linux 下可通过
stat -c "%y" path手动验证实际存储的时间精度
std::filesystem 在 C++17 中默认不启用,需要显式开启编译器支持
即使头文件 <filesystem> 存在,链接阶段仍可能失败,报错类似 undefined reference to 'std::filesystem::status'。这是因为标准库实现(如 libstdc++、libc++)需额外链接底层 OS 接口。
- GCC 9+ 需加编译选项
-lstdc++fs(注意是小写 L,不是数字 1) - Clang 与 libc++ 需
-lc++experimental(旧版)或-lc++fs(新版本) - CMake 中推荐用
target_link_libraries(my_target PRIVATE stdc++fs)或更健壮的find_package(Threads REQUIRED); target_link_libraries(... ${CMAKE_THREAD_LIBS_INIT})(因 filesystem 依赖线程库) - MSVC 2019+ 默认支持,但项目属性中需确认“C++ 语言标准”设为 ISO C++17 标准或更高
这些细节不解决,file_size 和 last_write_time 看似调用成功,实则链接时报错,容易误以为是代码逻辑问题。

















