【问题标题】:Compare two times in C在 C 中比较两次
【发布时间】:2015-07-26 05:23:22
【问题描述】:

如何比较 C 中的时间? 我的程序正在获取 2 个文件的最后修改时间,然后比较该时间以查看哪个时间是最新的。 是否有一个比较时间的功能,或者您必须自己创建一个?这是我的获取时间功能:

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

【问题讨论】:

  • 它可能是特定于操作系统的。我猜你正在使用 Linux 或一些 POSIX 系统。

标签: c datetime compare


【解决方案1】:

使用time.h 中的difftime(time1, time0) 得到两次之间的差。这将计算 time1 - time0 并返回一个 double 表示以秒为单位的差异。如果是肯定的,那么time1 晚于time0;如果是否定的,time0 稍后;如果为 0,它们是相同的。

【讨论】:

    【解决方案2】:

    您可以比较两个 time_t 值来找出哪个更新:

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <sys/stat.h>
    
    static time_t getFileModifiedTime(const char *path)
    {
        struct stat attr;
        if (stat(path, &attr) == 0)
        {
            printf("%s: last modified time: %s", path, ctime(&attr.st_mtime));
            return attr.st_mtime;
        }
        return 0;
    }
    
    int main(int argc, char **argv)
    {
        if (argc != 3)
        {
            fprintf(stderr, "Usage: %s file1 file2\n", argv[0]);
            return 1;
        }
        time_t t1 = getFileModifiedTime(argv[1]);
        time_t t2 = getFileModifiedTime(argv[2]);
        if (t1 < t2)
            printf("%s is older than %s\n", argv[1], argv[2]);
        else if (t1 > t2)
            printf("%s is newer than %s\n", argv[1], argv[2]);
        else
            printf("%s is the same age as %s\n", argv[1], argv[2]);
        return 0;
    }
    

    如果你想知道两个值之间的秒数差异,那么你需要正式使用difftime(),但实际上你可以简单地将两个time_t值相减。

    【讨论】:

      【解决方案3】:

      你可以使用下面的方法

      double difftime (time_t end, time_t beginning);
      

      它以秒为单位返回时差。你可以找到example here.

      【讨论】:

        【解决方案4】:

        我的代码:

        char * findLeastFile(char *file1, char *file2){
            struct stat attr1, attr2;
            if (stat(file1, &attr1) != 0 || stat(file2, &attr2) != 0)
            {
                printf("file excetion");
                return NULL;
            }
            if(difftime(attr1.st_mtime,attr2.st_mtime) >= 0)
                return file1;
            else 
                return file2;
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-11-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-18
          • 2015-04-21
          • 2010-11-21
          相关资源
          最近更新 更多