【问题标题】:Adding a few seconds of offset to stat()向 stat() 添加几秒钟的偏移量
【发布时间】:2017-05-08 20:08:41
【问题描述】:

我正在使用 stat 获取文件的最后修改时间,但我想在总时间上增加几秒钟。

if (stat(file_path, &st) == 0)
{
    char estimate_time[50];
    strftime(estimate_time, 50, "\'%F %T\'", localtime(&st.st_mtime)
}

所以,这段代码可以很好地获取文件的最后修改时间,但我只想在总时间上增加几秒钟。有没有办法在几秒钟内获得“st_mtime”,所以我可以简单地添加到该值,然后使用 strftime 转换为格式化输出?

谢谢

【问题讨论】:

标签: c time offset stat strftime


【解决方案1】:

要向struct tm 添加几秒钟,只需添加到tm_sec 成员并调用mktime() 以规范化结构。

  struct stat st;
  struct tm *tm = localtime(&st.st_mtime);
  if (tm == NULL) Handle_Error();
  tm->tm_sec += offset;
  time_t time_new = mktime(tm);  // adjust fields.
  if (time_new == (time_t) -1) Handle_Error();
  strftime(estimate_time, sizeof estimate_time, "\'%F %T\'", tm);

根据[stat] 标签,OP 位于要求time_t 以秒为单位的POSIX 系统上,因此POSIX 代码可以添加到st.st_mtime

  time_t new_time = st.st_mtime + offset;
  struct tm *tm = localtime(&new_time);
  if (tm == NULL) Handle_Error();
  strftime(estimate_time, sizeof estimate_time, "\'%F %T\'", tm);

【讨论】:

  • POSIX 要求 time_t 以秒为单位,那么您为什么不自信呢?
  • &st.st_mtime + offset 不正确。您正在添加到它的地址,而不是它的值。
  • @Barmar OP 的帖子可能符合 POSIX 标准,但没有这样说明或标记。如果是这样,我会这样回答。
  • @chux 他正在使用stat() 函数——这意味着它是POSIX。
  • @Barmar 一个合理的结论,但只是一个暗示——即使是一个很好的结论。其他平台可能会以非 POSIX 方式使用 stat()
猜你喜欢
  • 2011-07-25
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
相关资源
最近更新 更多