这两天遇到一个问题,需要设置一个时间戳文件,并且需要在需要的时候更新该时间戳文件,并比较上一次更新时间以及此次更新时间的差值,并打印出来。
下面是简单的步骤,相关代码如下:
#include <utime.h>
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#define TIME_STAMP "/root/charliye/time_flag"
main()
{
struct stat buf1;
struct stat buf2;
time_t t_old,t_old1,t_now,t_new;
stat(TIME_STAMP , &buf1); //获取时间戳文件的相关信息存到buf1
t_old = buf1.st_mtime;
t_old1 = buf1.st_atime;
printf("the last modify time is : %u,%u\n", t_old,t_old1);
t_now = time(NULL);
printf("the current time is : %u\n", t_now);
int ret = utimes(TIME_STAMP, NULL); //更新时间戳文件为当前时间
stat(TIME_STAMP, &buf2); //获取当前时间戳文件的相关信息存到buf2
t_new = buf2.st_mtime;
printf("the new modify time is : %u\n", t_new);
}
程序运行结果如下:
[root@localhost charliye]# ./utime
the last modify time is : 1456380013,1456380013
the current time is : 1456380015
the new modify time is : 1456380015
[root@localhost charliye]# ./utime
the last modify time is : 1456380015,1456380015
the current time is : 1456380021
the new modify time is : 1456380021
[root@localhost charliye]# ./utime
the last modify time is : 1456380021,1456380021
the current time is : 1456380031
the new modify time is : 1456380031
[root@localhost charliye]# ./utime
the last modify time is : 1456380031,1456380031
the current time is : 1456380044
the new modify time is : 1456380044