获取Linux中的文件的最后修改时间 [英] Get last modified time of file in linux
问题描述
我工作的一个C程序,我需要获得文件的最后修改时间。什么程序做一个函数通过每个文件循环目录中,当一个特定的文件(S)被发现,调用另一个函数来检查文件的最后修改时间。
I am working on a C program where I need to get the last modified time of the file. What the program does is a function loops through each file within a directory and when a particular file(s) is found it calls another function to check that the last modified times of the file.
在目录中有一个mylog.txt.1,mylog.txt.2和mylog.txt.3等。当我使用ll命令,我可以看到mylog.txt.1和mylog列出目录在linux .txt.2进行了修改,在5月4日和mylog.txt.3被体改于5月3日。
Within the directory there is a mylog.txt.1, mylog.txt.2 and mylog.txt.3 etc. When I list the directory in linux using the ll command I can see that mylog.txt.1 and mylog.txt.2 were modified on the 4th May and mylog.txt.3 was modifed on the 3rd May.
当程序检查每个文件然而,它总是返回5月3日的。下面是code,我使用。
When the program checks each of these files however, it is always returning 3rd may. Below is the code that I am using.
void getFileCreationTime(char *filePath)
{
struct stat attrib;
stat(filePath, &attrib);
char date[10];
strftime(date, 10, "%d-%m-%y", gmtime(&(attrib.st_ctime)));
printf("The file %s was last modified at %s\n", filePath, date);
date[0] = 0;
}
我试过 st_ctime
,即 st_mtime
和 st_atime的所有不同的变化
,但他们都返回5月3日。
I've tried all the different variations of st_ctime
, i.e. st_mtime
and st_atime
but they all return 3rd may.
感谢您的帮助,您可以提供。
Thanks for any help you can provide.
推荐答案
这是其中的情况下,时区的关系之一。你得到 gmtime的
的 st_mtime
。而应该使用本地时间
即
This is one of those cases where timezones matter. You're getting gmtime
of the st_mtime
. You should instead be using localtime
viz.
strftime(date, 20, "%d-%m-%y", localtime(&(attrib.st_ctime)));
这是因为 LS
使用您的时区的信息,当你使用 gmtime的
作为展示的一部分,它有意省略任何时区信息。
this is because ls
uses your timezone information, and when you used gmtime
as part of the display, it deliberately omitted any timezone information.
这篇关于获取Linux中的文件的最后修改时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!