【问题标题】:Last modified time of file in C [duplicate]C中文件的最后修改时间[重复]
【发布时间】:2017-05-08 02:32:50
【问题描述】:

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

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 而不是 localtime,但它不会产生正确的输出。使用“ls -l”显示正确的月、日和年...所以我不确定我做错了什么。

【问题讨论】:

  • '%Y-%m-%d %H:%M:%S" 改为"%Y-%m-%d %H:%M:%S"
  • 您是否检查过stat() 调用是否有效。如果不是,您正在使用随机数据。

标签: c linux time strftime


【解决方案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

【讨论】:

    猜你喜欢
    • 2012-09-11
    • 2017-03-23
    • 2016-09-06
    • 1970-01-01
    • 2015-09-09
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    相关资源
    最近更新 更多