【问题标题】:Format specifier for printing contents of "stat" buffer打印“stat”缓冲区内容的格式说明符
【发布时间】:2015-05-07 10:26:47
【问题描述】:

我在 linux 上使用 stat() 函数来检索有关文件的详细信息。
其中一个细节是存储在变量“st_atime”中的上次访问时间
但是显示此详细信息的格式说明符是什么。我的程序不断抛出错误。

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

int main()
{
  struct stat buf;
  stat("reversi.py",&buf);
  printf("The size  is...%d\n",buf.st_atime);
  return 0;
}

错误是

warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘__time_t’ [-Wformat=]
     printf("The size  is...%d\n",buf.st_atime);

这种数据的正确格式说明符是什么。
该函数还返回了更多详细信息。是否有一个地方我可以找到这些详细信息的所有正确格式说明符。?
谢谢。

【问题讨论】:

  • 使用例如strftime 将时间格式化为字符串。或related date/time functions 之一。
  • @JoachimPileborg 如果我必须转换所有细节,那会很乏味。有什么捷径吗?
  • 就是这样工作的,没有标准的printf格式来打印时间。
  • 关于分配的块数还有另一个细节。它的类型是 __blkcnt_t 。如何打印此详细信息。我无法在互联网上找到任何内容。
  • 搜索它的定义(它通常是在某些头文件中定义的typedef 别名,可能是&lt;sys/types.h&gt;)。或者只是尝试不同的printf 格式代码,例如"%ld""%llu""%hd" 等。

标签: c linux unix operating-system stat


【解决方案1】:

ctime()gmtime()localtime() 函数都采用 time_t 数据类型。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include<sys/stat.h>
#include <time.h>

int main()
{
    struct stat buf;
    stat("1.c",&buf);
    printf("Last Access was :  %s\n",ctime(&buf.st_atime));
    return 0;
}

这将打印出来

Last Access was :  Tue Apr 28 10:09:15 2015

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-25
    • 2013-05-20
    • 2014-05-30
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    相关资源
    最近更新 更多