在C++开发中,获取文件的精确时间戳是很多场景下的常见需求,尤其是需要微秒级精度的场景,比如文件变更监控、高频操作日志关联等。C++17标准引入的filesystem库提供了统一的文件操作接口,能够直接读取文件的各类时间属性,结合时间处理工具可以实现微秒级时间戳的提取。

filesystem时间接口基础
C++的filesystem库中,std::filesystem::path用于表示文件路径,std::filesystem::file_time_type是文件时间的专用类型,通过last_write_time函数可以获取文件的最后修改时间,而文件的创建时间和最后访问时间可以通过status函数获取的文件状态来提取。
需要注意的是,不同操作系统对文件时间的支持存在差异,Windows系统原生支持文件创建时间,而Linux系统下部分文件系统可能不记录文件创建时间,此时获取到的创建时间会和最后修改时间一致。
微秒级时间戳转换实现
file_time_type默认的时间精度取决于系统实现,要获取微秒级时间戳,需要将其转换为std::chrono::time_point的微秒精度类型,再计算从 epoch 开始的微秒数。以下是完整的实现代码:
#include <iostream>
#include <filesystem>
#include <chrono>
#include <ctime>
namespace fs = std::filesystem;
using namespace std::chrono;
// 获取文件创建时间的微秒级时间戳
long long get_file_create_time_us(const fs::path& file_path) {
try {
// 获取文件状态
fs::file_status status = fs::status(file_path);
// 提取文件创建时间,不同系统支持情况不同
fs::file_time_type create_time = status.creation_time();
// 转换为系统时钟的时间点
auto sys_time = time_point_cast<microseconds>(clock_cast<system_clock>(create_time));
// 计算从epoch开始的微秒数
auto epoch = sys_time.time_since_epoch();
return duration_cast<microseconds>(epoch).count();
} catch (const fs::filesystem_error& e) {
std::cerr << "获取文件创建时间失败: " << e.what() << std::endl;
return -1;
}
}
// 获取文件最后访问时间的微秒级时间戳
long long get_file_access_time_us(const fs::path& file_path) {
try {
// 获取文件状态
fs::file_status status = fs::status(file_path);
// 提取文件最后访问时间
fs::file_time_type access_time = status.last_access_time();
// 转换为系统时钟的时间点
auto sys_time = time_point_cast<microseconds>(clock_cast<system_clock>(access_time));
// 计算从epoch开始的微秒数
auto epoch = sys_time.time_since_epoch();
return duration_cast<microseconds>(epoch).count();
} catch (const fs::filesystem_error& e) {
std::cerr << "获取文件访问时间失败: " << e.what() << std::endl;
return -1;
}
}
int main() {
fs::path target_file = "test.txt";
// 先创建测试文件
std::ofstream out(target_file);
out << "测试文件内容" << std::endl;
out.close();
long long create_us = get_file_create_time_us(target_file);
long long access_us = get_file_access_time_us(target_file);
if (create_us != -1) {
std::cout << "文件创建时间微秒级时间戳: " << create_us << std::endl;
}
if (access_us != -1) {
std::cout << "文件最后访问时间微秒级时间戳: " << access_us << std::endl;
}
// 清理测试文件
fs::remove(target_file);
return 0;
}
关键代码说明
fs::status(file_path)用于获取文件的完整状态信息,包含各类时间属性creation_time()和last_access_time()分别返回文件的创建时间和最后访问时间,类型为file_time_typeclock_cast<system_clock>用于将文件时间转换为系统时钟的时间点,保证时间基准统一time_point_cast<microseconds>将时间点转换为微秒精度,再通过time_since_epoch获取从 epoch 开始的时长,最后转换为微秒数
注意事项
首先,编译时需要开启C++17及以上标准,比如使用g++编译时添加-std=c++17参数。其次,Linux系统下如果文件系统不支持记录创建时间,creation_time()返回的时间会和最后修改时间相同,需要在使用前确认系统环境。另外,文件时间受系统时钟影响,如果系统时间被调整,获取到的文件时间戳也会对应变化。
C++filesystem微秒级时间戳文件创建时间文件访问时间修改时间:2026-07-12 08:57:21