2017-05-08 39 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