文章目录
核心理论
时间类型
- 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。time
和localtime
函数需要头文件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;}