Linux时间相关笔记
系统时间获取
time_t time(time_t *tloc); //获取时间戳
struct tm *gmtime(const time_t *timep); //通过时间戳获取时间结构体
struct tm *gmtime_r(const time_t *timep, struct tm *result);
struct tm *localtime(const time_t *timep); //通过时间戳获取时间结构体
struct tm *localtime_r(const time_t *timep, struct tm *result);
time_t mktime(struct tm *tm); //通过时间结构体获取时间戳
size_t strftime(char *s, size_t max, const char *format,const struct tm *tm); //按特定格式输出时间
tail -f xxx//动态查看文件内容
获取系统时间向指定文件每秒存储一次数据。
示例1:timelog.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#define TIMELOG "/tmp/out" //timelog文件
int main()
{
FILE *fd;
int countLine=0;
size_t maxSize=1024;
char *buff;
time_t currentTime;
struct tm *tmRes;
fd = fopen(TIMELOG,"a+"); //以追加的方式打开文件
if(fd == NULL)
{
perror("fopen()");
exit(1);
}
while(getline(&buff,&maxSize,fd) >0) //读取文件行数
{
countLine++;
}
while(1)
{
currentTime = time(NULL); //获取当前时间戳
f(currentTime == ((time_t) -1))
{
perror("time()");
exit(1);
}
tmRes = localtime(¤tTime); //将时间戳转换为时间结构体
fprintf(fd,"%-4d %d-%d-%d %d:%d:%d\n",\
++countLine,tmRes->tm_year+1900,tmRes->tm_mon+1,tmRes->tm_mday\
,tmRes->tm_hour,tmRes->tm_min,tmRes->tm_sec); //将时间按特定格式写入文件
fflush(fd); //刷新文件数据流
sleep(1); //延时一秒
}
fclose(fd); //关闭文件
exit(0);
}
当前时间100天后
示例2:100days.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXSZIE 1024
int main(void)
{
time_t currentTime;
char timeStr[MAXSZIE];
struct tm *tmRes;
currentTime = time(NULL); //获取当前时间戳
if(((time_t) -1) == currentTime)
{
perror("time()");
exit(1);
}
tmRes = localtime(¤tTime); //通过时间戳获取时间结构体
if(tmRes == NULL)
{
printf("loacltime error\n");
exit(1);
}
strftime(timeStr,MAXSZIE,"Time:%Y-%m-%d %H:%M:%S",tmRes); //按特定格式输出时间
puts(timeStr);
tmRes->tm_mday +=100; //时间天数上加100天
mktime(tmRes); //调整时间结构体
strftime(timeStr,MAXSZIE,"100days later:%Y-%m-%d %H:%M:%S",tmRes); //按特定格式输出时间
puts(timeStr);
exit(0);
}