IO day2

一、思维导图

二、练习题

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

#include<myhead.h>
int main(int argc, const char *argv[])
{

	//定义日志计数器文件指针
	FILE *log = NULL;
	if((log = fopen("./daily_log","r")) == NULL)
	{
		perror("fopen error");
		return -1;
	}
	//定义容器接收日志文件计数次数
	long count = 1;
	fread(&count,sizeof(count),1,log);

	//关闭文件
	fclose(log);

	//定义两个容器存储时间信息和更新时间信息	
	char new_time[128] = "";
	char old_time[128] = "";
	while(1)
	{	
		//定义变量存储秒数
		time_t sys_time = time(NULL);

		//将秒数转换为结构体
		struct tm *time_ptr = localtime(&sys_time);

		snprintf(new_time,sizeof(new_time),"%4d-%2d-%2d %2d:%2d:%2d\n",\
				time_ptr->tm_year+1900,\
				time_ptr->tm_mon+1,\
				time_ptr->tm_mday,\
				time_ptr->tm_hour,\
				time_ptr->tm_min,\
				time_ptr->tm_sec);

		//新时间与旧时间不相等
		if(strcmp(new_time,old_time) != 0)
		{
			//输出时间
			printf("%ld:%s\n",count,new_time);

			count++;
			//将count重新写入日志文件计数器
			//定义日志计数器文件指针
			FILE *log = NULL;
			if((log = fopen("./daily_log","w")) == NULL)
			{
				perror("fopen error");
				return -1;
			}

			fwrite(&count,sizeof(count),1,log);
			
			//关闭文件
			fclose(log);
			//更新时间信息容器
			strcpy(old_time,new_time);
		}

	}

	return 0;
}

2、使用fread、fwrite完成两个文件的拷贝(不允许只读写一次)

#include<myhead.h>
int main(int argc, const char *argv[])
{
	//判断终端输入
	if(argc != 3)
	{
		printf("输入格式错误,请重新输入\n");
		printf("useage:./a.out srcname,destname\n");
	}

	//定义文件指针
	FILE *src = NULL;
	FILE *dest = NULL;

	if((src = fopen(argv[1],"r")) == NULL)
	{
		perror("src file fopen error");
		return -1;
	}

	if((dest = fopen(argv[2],"w")) == NULL)
	{
		perror("dest file fopen error");
		return -1;
	}


	//定义容器存储读取的数据
	char buf[128] = "";

	//将数据存入容器并读取到目标文件中
	int res = 0;
	do
	{
		res = fread(buf,1,sizeof(buf),src);
		fwrite(buf,1,res,dest);
	}while(res == 128);

	printf("拷贝成功\n");

	//关闭文件
	fclose(src);
	fclose(dest);
	return 0;
}

3、 实现对bmp图像的读写操作

#include<myhead.h>
int main(int argc, const char *argv[])
{
	//定义文件指针
	FILE *fp = NULL;
	if((fp = fopen("./gg.bmp","r+")) == NULL)
	{
		perror("fopen error");
		return -1;
	}

	//获取文件大小
	int img_size = 0;

	//将文件光标偏移两个字节
	fseek(fp,2,SEEK_SET);

	//读取4字节内容
	fread(&img_size,sizeof(img_size),1,fp);

	printf("size = %d\n",img_size);

	//从头向前偏移54字节
	fseek(fp,54,SEEK_SET);

	//更改像素
	unsigned char color[3] = {255,255,0};
	for(int i=0;i<960/2;i++)
	{
		for(int j=0;j<1280;j++)
		{
			fwrite(color,sizeof(color),1,fp);
		}
	}
	return 0;
}

4、 给图像打马赛克

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值