LINUX 时间编程

核心理论

时间类型

  • Coordinated Universal Time(UTC):世界标准时间,也就是大家所熟知的格林威治标准时间(Greenwich Mean Time,GMT)。
  • Calendar Time:日历时间,是用“从一个标准时间点(如:1970年1月1日0点)到此时经过的秒数”来表示的时间。

函数学习 - 时间操作

获取日历时间 time - get time in seconds

#include <time.h>
#include <stdio.h>

void main(){
	time_t ctime;
	ctime = time(NULL);
	
	printf("ctime is %d\n", ctime);}

获取本地时间 localtime - transform date and time to broken-down time or ASCII

#include <time.h>
#include <stdio.h>

void main(){
	time_t ctime;
	struct tm *localtm;

	/* 获取日历时间 */
	ctime = time(NULL);

	/* 将日历时间转化为本地时间 */
	localtm = localtime(&ctime);

	printf("now local is hour %d, min %d\n", localtm->tm_hour, localtm->tm_min);}

思考

编程读写一个文件 test.txt,每隔 1 秒向文件中写入一行数据,

类似这样:

1,  2007-7-30 15:16:42  
2,  2007-7-30 15:16:43

该程序应该无限循环,直到按 Ctrl-C 中断程序。

再次启动程序写文件时可以追加到原文件之后,并且序号能够接续上次的序号,

比如:

1,  2007-7-30 15:16:42
2,  2007-7-30 15:16:43
3,  2007-7-30 15:19:02
4,  2007-7-30 15:19:03
5,  2007-7-30 15:19:04

提示:

要追加写入文件,同时要读取该文件的内容以决定下一个序号是几,应该用什么模式打开文件?

首先判断一下打开的文件是否为新文件,如果是新文件,就从序号 1 开始写入;如果不是新文件,则统计原来有多少行,比如有 n 行,然后从序号 n+1 开始写入。以后每写一行就把行号加 1。

获取当前的系统时间需要调用函数 time(),得到的结果是一个 time_t 类型,其实就是一个大整数,其值表示从 UTC 时间 1970 年 1 月 1 日 00:00:00(称为 UNIX 的 Epoch 时间)到当前时刻的秒钟数。然后调用 localtime()time_t 所表示的 UTC 时间转换为本地时间(我们是 +8 区,比 UTC 多 8 个小时)并转成 struct tm 类型,该类型的各数据成员分别表示年月日时分秒,请自己写出转换格式的代码,不要使用 ctime()asctime() 函数。具体用法请查阅 man page。timelocaltime 函数需要头文件 time.h

调用 sleep(n) 可使程序睡眠 n 秒,该函数需要头文件 unistd.h

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#define err_log(errmsg) do{perror(errmsg); exit(1);}while(0)

int main(int argc, const char *argv[]){
	FILE *fp = freopen("./test.txt","a+",stdout);
	if(NULL == fp)
		err_log("fail to fopen");

	time_t sec = 0;
	int line = 1;
	
	//重定向读取行数
	char linech[2] = {};
	fseek(fp, -22, SEEK_END);
	linech[0] = fgetc(fp);
	linech[1] = fgetc(fp);
	line = atoi(linech);
	
	//使用fgets计算行数
/*	char buf[8] = {};
	while(fgets(buf,8,fp) != NULL){
		if(buf[strlen(buf) - 1] == '\n')
			line++;}
*/	
	//按字符计算行数
/*	rewind(fp);
	char ch;
	while(!feof(fp) && !ferror(fp)){
		ch = fgetc(fp);
		if('\n' == ch)
			line++;}
*/	
	while(1){
		sec = time(NULL);
		struct tm *time = localtime(&sec);
		
		printf("%2d %d-%2d-%2d %2d:%2d:%2d\n", line++,\
		time->tm_year + 1900, time->tm_mon + 1, time->tm_mday,\
		time->tm_hour, time->tm_min, time->tm_sec);
		fflush(fp);
		
		sleep(1);}
	
	return 0;}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值