IO作业day2

作业:

1>获取系统时间并写入文件,在停止程序后,再次运行程序,行号与前面行号相连

2> 使用fread、fwrite完成两个文件的拷贝

1:

#include <myhead.h>
#include <time.h>
int get_line(FILE *fp)
{
	//获取行号
	char buf[5];
	int count=0;
	while(fgets(buf,sizeof(buf),fp)!=NULL)
	{
		if(buf[strlen(buf)-1]=='\n')
		{
			count++;
		}
	}
	return count;
}
int main(int argc, const char *argv[])
{
	//打开文件
	FILE *fp;
	if((fp=fopen("./time.txt","a+"))==NULL)
	{
		perror("fopen error");
		return -1;
	}
	//定义一个系统时间变量
    time_t sysTime = time(NULL);
	int line=get_line(fp);
	while(1)
	{
		time(&sysTime);
		struct tm *tm_ptr=localtime(&sysTime);
		line++;
		fprintf(fp,"[%d] %4d-%d-%2d %02d:%02d:%02d\n",\
					line,\
					tm_ptr->tm_year+1900,\
					tm_ptr->tm_mon+1,\
					tm_ptr->tm_mday,\
					tm_ptr->tm_hour,\
					tm_ptr->tm_min,\
					tm_ptr->tm_sec);
		fflush(fp);
		sleep(1);
	}
	fclose(fp);
	return 0;
}

结果1:

 结果2:

 

2:

#include <myhead.h>
int main(int argc, const char *argv[])
{
	FILE *fp_y;
	if((fp_y=fopen("./password.txt","r"))==NULL)
	{
		perror("fopen error");
		return -1;
	}
	FILE *fp_c;
	if((fp_c=fopen("./zuoye1.txt","w"))==NULL)
	{
		perror("fopen error");
		return -1;
	}
	char buf[100]={0};
	while(1)
	{
		//置空数组
		memset(buf,0,sizeof(buf));
		//读取源文件内容
		fread(buf,sizeof(buf),1,fp_y);
		//将原文件写入新文件
		fwrite(buf,sizeof(buf),1,fp_c);
		//判断是否读取完成
		if(feof(fp_y))
		{
			break;
		}
		if(ferror(fp_y))
		{
			break;
		}
	}
	fclose(fp_y);
	fclose(fp_c);
	printf("拷贝成功!\n");
	return 0;
}

结果:

 思维导图:https://mubu.com/app/edit/home/6P1_TVHx6LD#m

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值