要求创建一个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退出程序,过一会儿之后重新启动程序
[1]2022-07-28 17:15:06
[2]2022-07-28 17:15:07
[3]2022-07-28 17:15:08
[4]2022-07-28 17:16:31
[5]2022-07-28 17:16:32
#include<stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
int line(FILE* fp)
{
int count=1;
char c=0;
while((c=fgetc(fp))!=EOF)
{
if('\n'==c)
{
count++;
}
}
return count;
}
int main(int argc, const char *argv[])
{
FILE* fp=fopen("./time.txt","a+");
if(NULL==fp)
{
perror("fopen");
return -1;
}
time_t t;
struct tm *p;
int count;
count=line(fp);
while(1)
{
t=time(NULL);
p=localtime(&t);
fprintf(fp,"[%d] %4d-%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);
printf("[%d] %4d-%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);
count++;
fflush(fp);
sleep(1);
}
fclose(fp);
return 0;
}
结果: