Get last modified file time in linux

I am working on a C program where I need to get the last modified file time. What the program does is a function that goes through each file in the directory, and when a certain file (s) is found, it calls another function to check if the last modified times of the file are.

Inside the directory there are mylog.txt.1 , mylog.txt.2 and mylog.txt.3 etc. When I list the directory in linux with the ll command, I see that mylog.txt.1 and mylog.txt.2 were changed on May 4 and mylog.txt.3 was changed on May 3.

If the program checks each of these files, it always returns on May 3rd. Below is the code I'm 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; } 

I tried all the different st_ctime options, i.e. st_mtime and st_atime , but they all return on May 3rd.

Thanks for any help you can provide.

+8
c linux timestamp
source share
3 answers

This is one of those times when time is important. You get gmtime st_mtime . You should use localtime instead.

 strftime(date, 20, "%d-%m-%y", localtime(&(attrib.st_ctime))); 

this is because ls uses your time zone information, and when you used gmtime as part of the display, it intentionally omitted any time zone information.

+9
source share

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)); } 
+9
source share

What to fix:

  • Use the correct field i.e. st_ctime
  • Make sure stat() succeeds before using its result.
  • Use strftime(date, sizeof date, ... to remove the risk of using the wrong buffer size.

At first, I suspected that your file system simply did not support tracking recently, but since you say that other tools manage to show this, I suspect that the code is breaking for some reason.

Could it be that the file names are not full path names, i.e. Do they not contain the correct directory prefix?

+3
source share

All Articles