Day2(Io进程)

该C程序创建并更新time.txt文件,每秒追加当前时间戳,格式为[序号]YYYY-MM-DDHH:MM:SS。程序在接收到Ctrl+C信号后不会立即删除之前记录的时间戳,重启后继续从上次的序号开始记录。
摘要由CSDN通过智能技术生成

作业

要求创建一个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

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int get_line(FILE *fp)
{
	int line = 0;
	char buf[100];

	fseek(fp, 0, SEEK_SET);

	while(1)
	{
		if(fgets(buf, sizeof(buf), fp) == NULL)
			break;
		if('\n' == buf[strlen(buf)-1])
			line++;
	}
	return line;
}

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)
	{
		time(&t1);
		info = localtime(&t1);
		int line = get_line(fp);
		fprintf(fp, "[%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);
		sleep(1);
	}

	fclose(fp);

	return 0;
}

运行结果:
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值