作业1:
要求创建一个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
main.c:
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int Count(FILE* fp)
{
int count=0;
fseek(fp,0,SEEK_END);
if(ftell(fp)==0)
{
return 0;
}
char str[20]="";
fseek(fp,0,SEEK_SET);
while(1)
{
if(fgets(str,sizeof(str),fp)==NULL)
{
break;
}
if('\n'==str[strlen(str)-1])
{
count++;
}
}
if(str[strlen(str)-1]!='\n')
{
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 t1=time(NULL);
struct tm *info = NULL;
while(1)
{
int i=Count(fp);
time(&t1);
info = localtime(&t1);
printf("%4d-%02d-%02d %02d-%02d-%02d\n",\
info->tm_year+1900,info->tm_mon+1,info->tm_mday,\
info->tm_hour,info->tm_min,info->tm_sec);
fprintf(fp,"[%d]%4d-%02d-%02d %02d-%02d-%02d\n",i,\
info->tm_year+1900,info->tm_mon+1,info->tm_mday,\
info->tm_hour,info->tm_min,info->tm_sec);
fflush(fp);
sleep(1);
}
fclose(fp);
return 0;
}
结果:
第一次运行:
第二次运行: