2017-05-08 84 views
0

我想在C/Linux中获取文件的最后修改时间,但时间总是出错。C中文件的最后修改时间

struct stat attrib; 
stat("/etc/example/file.txt", &attrib); 
char time[50]; 
strftime(time, 50, '%Y-%m-%d %H:%M:%S", localtime(&attrib.st_mtime)); 

打印时间给我“2024-05-01 15:35:21”。今年和明天显然是错误的。我尝试了不同的选项,例如gmtime而不是本地时间,但它不会产生正确的输出。使用“ls -l”显示正确的月份,日期和年份...所以我不确定我做错了什么。

+1

''%Y-%间 - %d%H:%M:%S “'变化到'” %Y-%间 - %d%H:%M:%S“' – eyllanesc

+0

没有符合你检查'stat()'调用是否奏效,如果没有,你使用随机数据。 –

回答

1

打印正确。

// try.c 

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

int main (int argc, char **argv) 
{ 
    struct stat attrib; 
    stat("file.txt", &attrib); 
    char time[50]; 
    strftime(time, 50, "%Y-%m-%d %H:%M:%S", localtime(&attrib.st_mtime)); 
    printf ("%s\n", time); 
} 

$ gcc -otry try.c 
$ ./try 
2017-05-08 08:43:42 

$ ls -ls file.txt 
4 -rw-rw-r-- 1 user1 user1 12 May 8 08:43 file.txt 
相关问题