IO进程线程练习

         要求创建一个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(&times);
		timep = localtime(&times);
		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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值