要求创建一个time.txt,存储内容格式如下:
[1] 2022-07-28 17:15:06
[2] 2022-07-28 17:15:07
[3] 2022-07-28 17:15:08 <------------------- ctrl + c退出程序,过一会儿之后重新启动程序
[4] 2022-07-28 17:16:31
[5] 2022-07-28 17:16:32
主函数
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#define ERRO(eof) { perror(eof); return -1; }
int main(int argc, const char *argv[])
{
//打开time.txt文件,不存在创建
FILE *fp = fopen("./time.txt","a+");
if (NULL == fp)
{
ERRO("fopen");
}
printf("fopen success\n");
long now_time = 0;
struct tm *p = NULL;
int count = 0;
char ch;;
while(1)
{
ch = fgetc(fp);
if (ch == 10)
{
count++;
}
else if(ch < 0)
{
break;
}
}
while (1)
{
count++;
now_time = time(NULL);
p = localtime(&now_time);
fprintf(fp,"[%2d] %04d-%02d-%02d %02d:%02d:%02d\n",\
count,p->tm_year+1900,p->tm_mon+1,\
p->tm_mday,p->tm_hour,p->tm_min,p->tm_sec);
fflush(fp);
sleep(1);
}
if (fclose(fp) < 0)
{
ERRO("fclose");
}
printf("fclose success\n");
return 0;
}
测试
root@VM-12-9-ubuntu:zouye# cat time.txt
[ 1] 2022-07-28 19:41:02
[ 2] 2022-07-28 19:41:03
[ 3] 2022-07-28 19:41:04
[ 4] 2022-07-28 19:41:05
[ 5] 2022-07-28 19:41:06 << 手动 CTRL + C 退出
[ 6] 2022-07-28 19:43:09
[ 7] 2022-07-28 19:43:10
[ 8] 2022-07-28 19:43:11
[ 9] 2022-07-28 19:43:12
[10] 2022-07-28 19:43:13
[11] 2022-07-28 19:43:14
[12] 2022-07-28 19:43:15
[13] 2022-07-28 19:43:16