首页 > 解决方案 > 设置文件访问时间、修改时间

问题描述

我有一个已安装驱动器中的文件列表。我正在尝试设置访问和修改时间。

这是使用utime修改前的stat信息

Access: 2020-07-28 15:06:51.000000000 +0530
Modify: 2020-07-28 15:06:51.000000000 +0530

使用 utime 后,这里是统计信息。

Access: 2020-07-28 21:20:47.-469639744
Modify: 2020-07-28 21:20:47.-469740064

这是代码

#include <stdio.h>
#include <utime.h>
#include <time.h>
#include <string.h>
#include <errno.h>

int main(void) {
    const char *filepath = "pathToFile/file";
    struct utimbuf ubuf;
    ubuf.actime = time(NULL) + (time_t)(6*60*60);
    ubuf.modtime = time(NULL) + (time_t)(6*60*60);
    errno = 0;
    int ret = utime(filepath, &ubuf);
    if (ret == -1) {
        printf("Error is: %s\n", strerror(errno));
    } else {
        puts("No Error!");
    }
    return 0;
}

我如何在这里保留+0530的时区信息?

标签: ctimeposix

解决方案


文件时间戳中没有存储时区信息(至少在我使用的文件系统中没有)。它只stat是以这种方式显示它。

相关代码来自stat.c human_time()

  if (localtime_rz (tz, &t.tv_sec, &tm))
    nstrftime (str, sizeof str, "%Y-%m-%d %H:%M:%S.%N %z", &tm, tz, ns);
  else
    {
      char secbuf[INT_BUFSIZE_BOUND (intmax_t)];
      sprintf (str, "%s.%09d", timetostr (t.tv_sec, secbuf), ns);
    }

在内部,所有 stat “知道”是struct timespec格式文件的时间戳,没有任何时区信息。如果从文件时间戳到struct tmin localtime_rz()call 的秒转换成功,则时间戳以包含%z时区信息的格式打印。如果调用失败,则"%s.%09d"使用 then。不存储时间戳,它是在stat显示有关文件的信息时从戳中推断(“猜测”)的。


推荐阅读