Get last modified time of file in linux

后端 未结 3 964
天命终不由人
天命终不由人 2020-12-09 09:57

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

相关标签:
3条回答
  • 2020-12-09 10:38

    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));
    }
    
    0 讨论(0)
  • 2020-12-09 10:50

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

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

    0 讨论(0)
  • 2020-12-09 11:00

    Things to fix:

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

    I first suspected that your filesystem simply didn't support tracking the last-modified time, but since you say that other tools manage to show it, I suspect the code is breaking for whatever reason.

    Could it be that the filenames are not full path names, i.e. they don't include the proper directory prefix?

    0 讨论(0)
提交回复
热议问题