How to get file modification time in c under multiple OS?

旧城冷巷雨未停 提交于 2019-12-30 07:14:10

问题


I'm trying to write a portable function in c that compares the last modified times of 2 files. The files are tiny and written one right after the other, so I need finer granularity than 1 second (milliseconds).
There seems to be a plethora of time/date functions...


回答1:


The C standard does not have any functions for this, but the Posix specification does. The 2008 edition even provides sub-second timestamps. #define _POSIX_C_SOURCE 200809L

The following code should give you an idea how to use it.

#define _POSIX_C_SOURCE 200809L
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <stdio.h> // for printf
#include <stdlib.h> // for EXIT_FAILURE

int main(int argc, char **argv)
{
    for (int i = 1; i < argc; ++i) {
        struct stat st = {0};
        int ret = lstat(argv[i], &st);
        if (ret == -1) {
            perror("lstat");
            return EXIT_FAILURE;
        }

        printf("%s: mtime sec=%lld nsec=%lld\n", argv[i],
               (long long) st.st_mtim.tv_sec, 
               (long long) st.st_mtim.tv_nsec);
    }

    return 0;
}



回答2:


You should look to the stat() function. It's available on *nix and on windows.

They will both return you a struct containing a field name st_msize. They are the finest functions I have heard of in order to get this kind of information from an Operating System.

Since you need portability, beware to take care of the various different types available on Windows. On *NIX, it's a classic time_t structure. If you include specific call, you can obtain nano seconds mtime: it was defined in POSIX.1-2008, according to the man page.

You can also take a look at how you can deal with 64/32 bit time_t




回答3:


For POSIX UNIX, stat() is portable and gives struct stat st_mtime which is the modification time in epoch seconds. Windows stat returns windows time values, and has creation time rather than st_ctime. For non-POSIX UNIX implementations, Windows and other OSes there is no portable concept of file modification time. So, depending on your idea of portable, this whole concept may or my not work for you.



来源:https://stackoverflow.com/questions/9342789/how-to-get-file-modification-time-in-c-under-multiple-os

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!