如何获得文件的修改时间在多个OS C? [英] How to get file modification time in c under multiple OS?

查看:136
本文介绍了如何获得文件的修改时间在多个OS C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C编写的便携式函数的两个文件的最后修改时间进行比较。该文件是微小的,在其他以后写一个正确的,所以我需要更细的粒度小于1秒(毫秒)。结果
似乎有时间/日期函数过多...

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...

推荐答案

C标准并没有这方面的任何功能,但POSIX规范一样。 2008年版甚至提供亚秒级的时间戳。 #定义_POSIX_C_SOURCE 200809L

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

以下code应该给你一个想法如何使用它。

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

这篇关于如何获得文件的修改时间在多个OS C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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