如何打印stat函数返回的日期和时间

mrg*_*mrg 0 c unix linux

程序:

#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
void main()
{
    struct stat stbuf;
    stat("alphabet",&stbuf);
    printf("Access time  = %d\n",stbuf.st_atime);
    printf("Modification time  = %d\n",stbuf.st_mtime);
    printf("Change time  = %d\n",stbuf.st_mtime);
}
Run Code Online (Sandbox Code Playgroud)

上面的程序给出了以下输出:

输出:

$ ./a.out 
Access time  = 1441619019
Modification time  = 1441618853
Change time  = 1441618853
$
Run Code Online (Sandbox Code Playgroud)

它以秒为单位打印日期.在C中,将时间打印为由stat函数返回的人类可读格式的方法是什么.返回类型stbuf.st_atime是__time_t.

提前致谢...

小智 7

尝试使用char*ctime(const time_t*timer); 函数来自time.h库.

#include <time.h>
#include<stdio.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
void main()
{
    struct stat stbuf;
    stat("alphabet",&stbuf);
    printf("Access time  = %s\n", ctime(&stbuf.st_atime));
    printf("Modification time  = %s\n", ctime(&stbuf.st_mtime));
    printf("Change time  = %s\n", ctime(&stbuf.st_mtime));
}
Run Code Online (Sandbox Code Playgroud)

它会给出以下结果:

$ ./test
Access time  = Mon Sep 07 15:23:31 2015

Modification time  = Mon Sep 07 15:23:31 2015

Change time  = Mon Sep 07 15:23:31 2015
Run Code Online (Sandbox Code Playgroud)