C 中的日期差异(秒)

Dates difference in C (seconds)

我从来没有用 C 编程过,因此编写一个 returns 两个日期之间以秒为单位的差异的小软件是一个真正的挑战。

作为背景信息,我在 Python 应用程序中实现了一种心跳,每 15 秒更新一个 txt 文件。现在我想创建一个 C 应用程序来不断检查这个 txt,如果差异大于 30 秒,它会重新启动我的计算机。

这就是我到目前为止的进展:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>


//Returns the number seconds since the last time the files has been updated
int lastUpdate() {
    struct stat attr;
    stat("watcher.txt", &attr);

    //Gets the last update in the following format: Mon Aug 13 08:23:14 2012
    //ctime(&attr.st_mtime);

    time_t lastChange = &attr.st_mtime
    time_t now = time(0)

    //No idea how to implement it :-(
    //int seconds = timediff(now, lastChange)

    return seconds;
}

//Constantly checks if application is sending heart beats in a 30 seconds time frame
main()
{
    while(1 == 1)
    {
        if(lastUpdate() > 30)
        {
            sprintf(cmd, "sudo reboot -i -p");
            system(cmd);
        }
    }
}

有人会这么友善并提供一些关于如何让它工作的提示吗? 非常感谢!

已编辑: 没有问题的最终代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>


//Returns the number seconds since the last time the files has been updated
int lastUpdate() {
    struct stat attr;
    stat("/home/pi/watcher.txt", &attr);
    time_t lastChange = attr.st_mtime;
    time_t now = time(0);
    int seconds = now - lastChange;
    return seconds;
}

//Constantly checks if application is sending heart beats in a 30 seconds time frame
main()
{
    sleep(120);

    while(1 == 1)
    {
        sleep(1);

        if(lastUpdate() > 30)
        {
            system("sudo reboot -i -p");
        }
    }
}

你走运了! time_t是一个数字,时间戳是从1970年开始的时间,以秒为单位。所以:

int seconds = now - lastChange;

哦,还有

time_t lastChange = &attr.st_mtime

应该是

time_t lastChange = attr.st_mtime

你只需要减去time_t,但你在这行有问题

time_t lastChange = &attr.st_mtime

因为stat.st_mtime的类型是time_t而不是time_t *,所以你应该把它改成

time_t lastChange = attr.st_mtime

然后

return new - lastChange;

此外,检查 stat("watcher.txt", &attr) != -1

time_t 通常 自 1970 年 1 月 1 日以来的秒数 0:00:00 UTC (GMT )。所以简单的减法就可以了。

time_t lastChange = &attr.st_mtime
time_t now = time(0)
time_t seconds = now - lastChange;
printf("%ll\n", (long long) seconds);

严格来说,time_t可能是其他标量。
一种便携式解决方案是使用 double difftime(time_t time1, time_t time0);

#include <time.h>
double seconds = difftime(now, lastChange);
printf("%f\n", seconds);