在C中比较两次

时间:2015-07-26 05:23:22

标签: c datetime compare

如何比较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));
}

4 个答案:

答案 0 :(得分:6)

使用difftime(time1, time0)中的time.h来获取两次之间的差异。这将计算time1 - time0并返回表示以秒为单位的差异的double。如果它是正面的,则time1晚于time0;如果是否定的,time0是后来的;如果为0,则它​​们相同。

答案 1 :(得分:4)

您可以比较两个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值。

答案 2 :(得分:2)

您可以使用以下方法

double difftime (time_t end, time_t beginning);

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

答案 3 :(得分:1)

我的代码:

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;

}