【问题标题】:Printing file size and time in C在 C 中打印文件大小和时间
【发布时间】:2015-10-20 10:14:15
【问题描述】:

我正在尝试打印文件的大小和上次访问、上次修改和上次更改的时间。但是我在终端中遇到错误。它表示 buf.st_size 的返回值的类型是 '__off_t' 类型,而 buf.st_atime、buf.st_mtime 和 buf.st_ctime 的返回值的类型是 '__time_t'。

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

int main(int argc, char** argv)
{

  struct stat buf;

  if(argc==2){
    stat(argv[1],&buf);

    if(S_ISDIR(buf.st_mode))
      printf("It's a directoy.\n");

    else if(S_ISREG(buf.st_mode))
      printf("It's a file.\n");

    else
      printf("It's other.\n");

   printf("User ID: %d.\nGroup ID: %d.\n",buf.st_uid,buf.st_gid);

   printf("Size in bytes: %zd .\n",buf.st_size);

   printf("Last access: %s.\nLast modification: %s.\nLast change:        %d.\n",buf.st_atime,buf.st_mtime,buf.st_ctime);

   exit(0);
 }
 printf("No argument was given.\n");
}

【问题讨论】:

  • 这里离题了,因为“调试我的代码”问题(没有任何直觉可能是错误的)。顺便说一句,您 RTFM stat(2) 仔细了吗?同时编译所有警告和调试信息 (gcc -Wall -Wextra -g) 并使用调试器 (gdb)。也可以使用stat(1) 命令
  • 您也没有检查stat() 调用是否成功。
  • @AndrewHenle 检查 stat() 调用是否成功是什么意思?

标签: c file printf file-structure


【解决方案1】:

time_t 只是一个整数,表示 1970 年 1 月 1 日之后的秒数。在现代系统上,它是一个 64 位整数,根据您的系统,您应该可以使用 %lu%llu。您还可以强制转换参数以匹配格式:

printf("Last access: %lu.\n", (long unsigned) buf.st_atime);

如果你想要一个字符串表示,你可以使用strftime。这个函数采用一种格式——如果你很懒,使用"%c"作为“首选”格式——一个要填充的字符缓冲区和一个struct tm,其中包含分解为人类可读信息的时间和日期。

要从time_t 时间戳中获取struct tm,请使用localtime。请务必为这些功能添加&lt;time.h&gt;

例如:

char str[32];

strftime(str, sizeof(str), "%c", localtime(&buf.st_atime));
printf("Last access: %s.\n", str);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多