Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

c - Get last modified time of file in linux

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.

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.

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;
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This worked fine for me:

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

void getFileCreationTime(char *path) {
    struct stat attr;
    stat(path, &attr);
    printf("Last modified time: %s", ctime(&attr.st_mtime));
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...