获取linux中文件的最后修改时间 [英] Get last modified time of file in linux

查看:53
本文介绍了获取linux中文件的最后修改时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 C 程序,我需要在其中获取文件的最后修改时间.程序所做的是一个函数循环遍历目录中的每个文件,当找到特定文件时,它会调用另一个函数来检查文件的最后修改时间.

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.1mylog.txt.2mylog.txt.3等.当我使用 ll 命令列出了 linux 中的目录我可以看到 mylog.txt.1mylog.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 modified on the 3rd May.

但是,当程序检查每个文件时,它总是返回 3rd may.下面是我正在使用的代码.

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
", filePath, date);
    date[0] = 0;
}

我已经尝试了 st_ctime 的所有不同变体,即 st_mtimest_atime 但它们都返回 3rd may.

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.

推荐答案

这是时区很重要的情况之一.您将获得 st_mtimegmtime.您应该改为使用 localtime 即.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆