I/O作业2

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

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

 代码:

#include<myhead.h>

int main(int argc, const char *argv[])
{
	//打开文件
	FILE *fp = fopen("log.txt", "a");
    if (fp == NULL) 
	{
        perror("文件打开错误!");
        return 1;
    }

	char buf[128] = "";      //存放转变后的字符串
	char auf[128] = "";
	int i = 1; 				//行号				
	
	while(1)
	{
		//定义变量存储秒数
    	time_t sys_time = time(NULL);
		
		//将秒数转换为结构体
		struct tm *time_ptr = localtime(&sys_time);
		
		//转换写入字符串
		snprintf( buf,sizeof(buf),"%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(auf,buf)!=0)
		{
			printf("%d、%s\n", i, buf);
			strcpy(auf, buf);
			fprintf(fp, "%d、%s\n", i, buf); 	//写入文件
			i++;
			fflush(fp);
		}
	}

	return 0;
}

运行结果:

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

代码:

#include<myhead.h>

int main(int argc, const char *argv[])
{
	//判断传入的文件个数
	if(argc != 3)
	{
		fputs("input file error\n", stderr);
		return -1;
	}
 
	//以只读的形式打开源文件
	FILE *sfp = NULL;
	if((sfp = fopen(argv[1], "r")) == NULL)
	{
		printf("fopen error %d,%s,%s\n", __LINE__, __func__, __FILE__);
		return -1;
	}
 
	//以只写的形式打开目标文件
	FILE *dfp = NULL;
	if((dfp = fopen(argv[2], "w")) == NULL)
	{
		perror("fopen error");
		return -1;
	}
 
	//定义搬运工
	char buf[128] = "";
	while(1)
	{
		int i = fread(buf, 1, sizeof(buf), sfp);   //从源文件中读取数据
		if(i==0)
		{
			break;
		}

		//将内容写入目标文件
		fwrite(buf, 1, i, dfp);
	}
 
	printf("拷贝成功\n");
 
	//关闭文件
	fclose(sfp);
	fclose(dfp); 
 
	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;
 
	//将文件光标偏移2个字节
	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] = {0, 0, 255};     //正红色
	for(int i=0; i<960/2; i++)          //外行
	{
		for(int j=0;j<1280; j++)       //内列
		{
			fwrite(color, sizeof(color), 1, fp);
		}
	} 
 
	//关闭文件
	fclose(fp);
 
	return 0;
}

运行结果:

4> 君子作业:给图像打马赛克

代码:

运行结果:

思维导图:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值