作业1
要求创建一个time.txt ,存储内容格式如下:
[1] 2023-02-22 18:25:55
[2] 2023-02-22 18:25:56
[3] 2023-02-22 18:25:57
[4] 2023-02-22 18:25:58
ctrl+c退出程序,过一会儿之后重启启动程序
[1] 2023-02-22 18:25:55
[2] 2023-02-22 18:25:56
[3] 2023-02-22 18:25:57
[4] 2023-02-22 18:25:58
[5] 2023-02-22 18:26:13
[6] 2023-02-22 18:26:14
[7] 2023-02-22 18:26:15
[8] 2023-02-22 18:26:16
[9] 2023-02-22 18:26:17
int main(int argc, const char *argv[])
{
FILE *fp = fopen("./time.txt","a+");
if(NULL == fp){
perror("fopen");
return -1;
}
int line=0;
time_t seconds;
char str[32]="";
while(1){
if(NULL == fgets(str,sizeof(str),fp)){
break;
}
if('\n'==str[strlen(str)-1]){
line++;
}
}
struct tm *info = NULL;
while(1){
time(&seconds);
info = localtime(&seconds);
line++;
sprintf(str,"[%d] %4d-%02d-%02d %02d:%02d:%02d\n",\
line,\
info->tm_year+1900,info->tm_mon+1,info->tm_mday,\
info->tm_hour,info->tm_min,info->tm_sec);
fputs(str,fp);
printf("%s",str);
fflush(fp);
sleep(1);
}
fclose(fp);
return 0;
}
执行结果
ubuntu@ubuntu:20230222$ ./a.out
[1] 2023-02-22 18:25:55
[2] 2023-02-22 18:25:56
[3] 2023-02-22 18:25:57
[4] 2023-02-22 18:25:58
^C
ubuntu@ubuntu:20230222$ cat time.txt
[1] 2023-02-22 18:25:55
[2] 2023-02-22 18:25:56
[3] 2023-02-22 18:25:57
[4] 2023-02-22 18:25:58
ubuntu@ubuntu:20230222$ ./a.out
[5] 2023-02-22 18:26:13
[6] 2023-02-22 18:26:14
[7] 2023-02-22 18:26:15
[8] 2023-02-22 18:26:16
[9] 2023-02-22 18:26:17
^C
ubuntu@ubuntu:20230222$ cat time.txt
[1] 2023-02-22 18:25:55
[2] 2023-02-22 18:25:56
[3] 2023-02-22 18:25:57
[4] 2023-02-22 18:25:58
[5] 2023-02-22 18:26:13
[6] 2023-02-22 18:26:14
[7] 2023-02-22 18:26:15
[8] 2023-02-22 18:26:16
[9] 2023-02-22 18:26:17