日期差异C(秒)

时间:2015-01-13 19:45:34

标签: c time

我从未在C编程,因此编写一小块软件是一个真正的挑战,它会以秒为单位返回两个日期之间的差异。

就像背景信息一样,我在Python应用程序中实现了一种心跳,每15秒更新一次txt文件。现在我想创建一个不断检查此txt的C应用程序,如果差异大于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);
        }
    }
}

有人会这么好,并提供一些如何使这个工作的提示? 非常感谢你!

EDITED: 最终代码无问题地工作:

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

3 个答案:

答案 0 :(得分:4)

你好运! time_t是一个数字,时间戳是自1970年初以来的时间,以秒为单位。所以:

int seconds = now - lastChange;

哦,

time_t lastChange = &attr.st_mtime

应该是

time_t lastChange = attr.st_mtime

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

您只需要减去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