IO流(2)

作业一:

写一个日志文件,将程序启动后,每一秒的时间写入到文件中

实现如下功能:

1、2024- 7-29 10:31:19

2、2024- 7-29 10:31:20

3、2024- 7-29 10:31:21

ctrl+c:停止程序

./a.out

4、2024- 7-29 10:35:06

5、2024- 7-29 10:35:07

6、2024- 7-29 10:35:08

int main(int argc, const char *argv[])
{
	FILE * file=fopen("./time.txt","a+");//追加方式打开文件
	int line=0;
	char rbuf[20]="";
	char *rdata=fgets(rbuf,sizeof(rbuf),file);
	while(rdata!=NULL){
		if(rdata[strlen(rdata)-1]=='\n'){ //只要读取的最后一个是空格就加1
			line++;
		}
	    rdata=fgets(rbuf,sizeof(rbuf),file);
	}
	line++;再次加1,因为要继续在下一行写
	time_t old_time=time(NULL);//旧时间
	while(1){
		time_t new_time=time(NULL);//新时间不断轮询更新
		if(new_time-old_time>=1){
			fprintf(file,"%d:",line);
			line++;
			struct tm * date=localtime(&new_time);
			char *buf=asctime(date);//转换为格式化的字符串
			fwrite(buf,strlen(buf),1,file);
			//fwrite("\n",1,1,file);
			fflush(file);//刷新缓存区
			old_time=new_time;//更新旧时间为新时间
		}
	}
	return 0;
}

 

作业二:

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

不允许只读写一次

int main(int argc, const char *argv[])
{
	if(argc!=3){
		return -1;
	}
	FILE *sfile=fopen(argv[1],"r");
	FILE *tfile=fopen(argv[2],"w");
	char data[10]="";
	int count=0;
	count=fread(data,1,sizeof(data),sfile);
	while(count>0){
		fwrite(data,1,count,tfile);
		count=fread(data,1,sizeof(data),sfile);
	}
	fclose(sfile);
	fclose(tfile);
	return 0;
}

作业三:

实现对bmp图像的读写操作

int main(int argc, const char *argv[])
{
	FILE* file=fopen("./gg.bmp","r+");

	int img_szie=0;
	fseek(file,2,SEEK_SET);
	fread(&img_szie,4,1,file);
	printf("%d\n",img_szie);
	
	fseek(file,54,SEEK_SET);
	unsigned char color[3]={0,255,0};
	for(int i=0;i<960/3;i++){
		for(int j=0;j<1280;j++){
			fwrite(color,sizeof(color),1,file);
		}
	}
	fclose(file);
	return 0;
}

作业四:

使用文件IO完成,将源文件中的所有内容进行加密(大写转小写、小写转大写)后写入目标文件中

源文件内容不变

void reverse(char *);

int main(int argc, const char *argv[])
{
	int sfile=open(argv[1],O_RDONLY);//打开源文件
	int tfile=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,06640);//打开目标文件
	char buf[10]="";//设置缓冲区
	int count=read(sfile,buf,sizeof(buf));//记录读取到的个数
	while(count!=0&&count!=-1){
		reverse(buf);//转换大小写
		write(tfile,buf,count);
		count=read(sfile,buf,sizeof(buf));//再次记录个数
	}
	return 0;
}

void reverse(char * data){
	for(int i=0;i<strlen(data);i++){
		if(data[i]>=65&&data[i]<=90){
			data[i]+=32;
		}else if(data[i]>=97&&data[i]<=122){
			data[i]-=32;
		}
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值