You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言开发中如何设置含纳秒精度的文件时间戳

根本原因

utime()接口及配套的struct utimbuf仅支持秒级时间精度,结构体的时间字段是只存秒数的time_t类型,没有预留亚秒(微秒、纳秒)的存储位,调用时会直接丢弃时间戳的小数部分,这就是123.213241的时间戳被截断为123.000000的原因。

实现方法

要保留纳秒级精度的时间戳,使用POSIX标准定义的纳秒级时间设置接口即可:

  • 基于文件路径操作时用utimensat()
  • 已经拿到目标文件打开的文件描述符时用futimens()

两个接口都通过struct timespec类型传递时间值,该结构包含tv_sec(秒数)和tv_nsec(纳秒数,取值范围0~999999999)两个字段,可以完整承接stat返回结果中st_atim(访问时间)、st_mtim(修改时间)的全精度时间值,不会丢失纳秒信息。

修正后的代码示例

#include <sys/stat.h>
#include <fcntl.h>

int sync_file_timestamp(const char* src_path, const char* dst_path) {
    struct stat src_stat;
    // 读取源文件元数据,必须检查返回值处理错误
    if (stat(src_path, &src_stat) != 0) {
        return -1;
    }

    // 时间数组固定长度为2:索引0存访问时间atime,索引1存修改时间mtime
    struct timespec new_ts[2];
    new_ts[0] = src_stat.st_atim; // 直接赋值完整timespec结构,完整保留纳秒
    new_ts[1] = src_stat.st_mtim;

    // 设置目标文件时间戳
    // AT_FDCWD表示目标路径是相对于当前进程工作目录的相对路径,无特殊需求flags参数填0即可
    if (utimensat(AT_FDCWD, dst_path, new_ts, 0) != 0) {
        return -1;
    }
    return 0;
}

注意点

  • 不要从st_atim/st_mtim中单独提取tv_sec字段赋值,必须传递完整的struct timespec结构才能保留纳秒信息
  • 旧的utimes()接口仅支持微秒级精度,无法满足纳秒保留需求,不要使用
  • 上述接口遵循POSIX.1-2008标准,Linux、macOS、BSD等主流类Unix系统均已原生支持,不需要额外安装依赖

内容的提问来源于stack exchange,提问作者programme3219873

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 21:27:25