杭州Day25_IO及其有关函数_20240729

一、相关函数练习

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

1> log.c

#include <myhead.h>

int main(int argc, const char *argv[])
{
	//定义文件指针
	FILE *fp = NULL;
	//以追加形式打开 log.txt 文件
	if((fp = fopen("log.txt", "a+")) == NULL)
	{
		perror("fopen error\n");
		return -1;
	}
	
	//定义变量记录行数
	int line = 0;
	char buf[128] = "";
	//读取文件,记录行数
	while(1)
	{
		//清空容器
        bzero(buf,  sizeof(buf));
        if( fgets(buf, sizeof(buf), fp)  == NULL)
        {
            break;    //说明文件读取结束
        }

        //行数变化
		line++;
	}

	//写入时间日志逻辑
	while(1)
	{
		//定义变量存储秒数
		time_t sys_time1,sys_time2;
		time(&sys_time1);
		//判断时间变化
		while(1)
		{
			time(&sys_time2);
			if(sys_time2 - sys_time1 >= 1)
			{
				break;
			}
		}
		
		//将秒数转换为结构体
		struct tm *time_ptr = localtime(&sys_time2);
		
		line++;
		fprintf(fp, "%6d. %4d-%2d-%2d %2d:%2d:%2d\n", 
			line,
			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);	
		fflush(fp);
	}

	return 0;
}

2.程序运行截图

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

1> 09test.c

#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("%s fopen error\n", argv[1]);
		return -1;
	}
	
	//定义目标文件指针,以只读的形式打开文件
	FILE *dfp = NULL;
	if((dfp = fopen(argv[2], "w")) == NULL)
	{
		printf("%s fopen error\n", argv[2]);
		return -1;
	}

	//定义搬运工
	char buf[12] = "";

	while(1)
	{
		if((fread(buf, sizeof(buf), 1, sfp) < 1))
		{
			break;
		}

		fwrite(buf, sizeof(buf), 1, dfp);
	}


	//关闭文件
	fclose(sfp);
	fclose(dfp);
	
	return 0;
}

2> 程序运行截图

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

1> bmp.c

#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 x=0; x<960; x++)          //外行
   {
        for(int y=0;y<1280; y++)       //内列
        {
			if((x%12==0) && (y%16==0))
			{
				for(int i=x; i<x+12&&i<960; i++)
				{
					fread(color, sizeof(color), 1, fp);
					for(int j=y; j<y+16&&j<1280; j++)
            		{	
						fwrite(color, sizeof(color), 1, fp);
					}
				}
			}
        }
    }
    
    //关闭文件
    fclose(fp);

    return 0;
}

2> 程序运行截图

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值