要求创建一个time.txt,存储内容格式如下:
[0] 2023-02-22 19:31:03
[1] 2023-02-22 19:31:04
[2] 2023-02-22 19:31:05
[3] 2023-02-22 19:31:06
[4] 2023-02-22 19:31:07
[5] 2023-02-22 19:31:08
[6] 2023-02-22 19:31:09
ctrl + c 退出程序,过一会儿后重新启动程序
[5] 2023-02-22 19:31:08
[6] 2023-02-22 19:31:09
[7] 2023-02-22 19:31:16 <--------------
[8] 2023-02-22 19:31:17
[9] 2023-02-22 19:31:18
[10] 2023-02-22 19:31:19
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int LineNow(char *k,FILE *p){
fseek(p,0,SEEK_SET);
int line = 0;
while(1){
if(fgets(k,sizeof(k),p) == NULL)
break;
for(int i = 0; i < strlen(k); i ++){
if(*(k+i) == '\n'){
line ++;
}
}
}
return line;
}
int main(int argc, const char *argv[])
{
FILE *p = fopen(argv[1],"a+");
if(NULL == p){
perror("fopen");
return -1;
}
char arr[5] = "\0";
int line = LineNow(arr,p);
printf("%d\n",line);
fseek(p,0,SEEK_END);
time_t times;
struct tm *timep;
while(1){
time(×);
timep = localtime(×);
fprintf(p,"[%d] %4d-%02d-%02d %02d:%02d:%02d\n",line,\
timep->tm_year+1900,timep->tm_mon+1,\
timep->tm_mday,timep->tm_hour,\
timep->tm_min,timep->tm_sec);
fflush(p);
sleep(1);
line ++;
}
fclose(p);
return 0;
}