在C中比较两次

PTN*_*PTN 5 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));
}
Run Code Online (Sandbox Code Playgroud)

Cal*_*leb 7

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


Jon*_*ler 5

您可以比较两个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;
}
Run Code Online (Sandbox Code Playgroud)

如果你想以秒为单位知道值之间的差异,那么你需要使用difftime()官方,但在实践中你可以简单地将两个time_t值相减。