Linux 时间戳

打印目前时间

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define BUFSIZE 1024
//打印当时时间
int main(int argc,char** a)
{
        time_t stamp;
        struct tm *tm;
        char buf[BUFSIZE];
        time(&stamp);
        tm=localtime(&stamp);
        //tm_year是从1900记起的,tm_mon范围是0-11所以要加一
        sprintf(buf,"%d-%d-%d %d:%d:%d",tm->tm_year+1900,\
                        tm->tm_mon+1,tm->tm_mday,tm->tm_hour,\
                        tm->tm_min,tm->tm_sec);
        puts(buf);

        exit(0);
}

在 /tmp/out目录下每秒追加一条时间信息

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>
#define FILEPATH "/tmp/out"
#define BUFSIZE 1024
int main(int argc, char** argv)
{
        time_t stamp;
        struct tm* tm;
        FILE *fp;
        char buf[BUFSIZE];
        int count=0;
        fp=fopen(FILEPATH,"a+");
        if(fp==NULL)
        {
                perror("fopen()");
                exit(1);
        }
        while(fgets(buf,BUFSIZE,fp)!=NULL)
        {
                count++;
        }
        while(1)
        {
                time(&stamp);
                tm=localtime(&stamp);
                 fprintf(fp,"%-4d%d-%d-%d %d:%d:%d\n",++count,tm->tm_year+1900,\
                        tm->tm_mon+1,tm->tm_mday,tm->tm_hour,\
                        tm->tm_min,tm->tm_sec);
                fflush(fp);
                sleep(1);
        }

        fclose(fp);
}

可以用命令行   tail -f /tmp/out  观察文件变化

tail -f /tmp/out

直接计算100天后的日期 用mktime 对 tm进行处理

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define BUFSIZE 1024
int main(int argc,char** argv)
{
        time_t stamp;
        struct tm* tm;
        char buf[BUFSIZE];
        time(&stamp);
        tm=localtime(&stamp);
        strftime(buf,BUFSIZE,"%Y-%m-%d",tm);
        puts(buf);
        //在日期加入100,用mktime会对tm进行修改的特性,day溢出会自动调整格式
        tm->tm_mday+=100;
        //tm经过该函数处理会调整成正常格式
        (void)mktime(tm);
        strftime(buf,BUFSIZE,"%Y-%m-%d",tm);
        puts(buf);

        exit(0);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值