要求创建一个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
程序代码
1 #include<stdio.h>
2 #include<time.h>
3 #include<stdlib.h>
4 #include<unistd.h>
5 #include<string.h>
6
7 int main(int argc, const char *argv[])
8 {
9 FILE *fp=fopen("./time.txt","a+");
10 if(NULL==fp)
11 {
12 perror("fopen");
13 return -1;
14 }
15 //找行数
16 fseek(fp,0,SEEK_SET);
17 char arr[100];
18 int line=1;
19
20 while(1)
21 {
22 if(fgets(arr,sizeof(arr),fp)==NULL)
23 break;
24 if('\n'==arr[strlen(arr)-1])
25 line++;
26 }
27 struct tm *Time=NULL;
28 time_t t1=time(NULL);
29 while(1)
30 {
31 time(&t1);
32 Time=localtime(&t1);
33 fprintf(fp,"[%d] %4d-%02d-%02d %02d:%02d:%02d\n",\
34 line,Time->tm_year+1900,Time->tm_mon+1,Time->tm_mday,\
35 Time->tm_hour,Time->tm_min,Time->tm_sec);
36 line++;
37 fflush(fp);
38 sleep(1);
39 }
40 return 0;
41 }
运行结果
txt文件中
1 [1] 2023-02-22 23:19:04
2 [2] 2023-02-22 23:19:05
3 [3] 2023-02-22 23:19:06
4 [4] 2023-02-22 23:19:13
5 [5] 2023-02-22 23:19:14
6 [6] 2023-02-22 23:19:15
7 [7] 2023-02-22 23:19:16