C语言标准I/O_fread/fwrite


好久不用,对C语言文件操作都有点生疏了,由于工作需要,稍稍的复习一下;

下面的程序用C语言的fread/fwrite来读取hex文件,并且拷贝,目的是拷贝后的文件需要和源文件不能有任何差异;

// Hex.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#define SIZE 512

int main(int argc, char* argv[])
{
	int i = 0;
	int cnt = 0;
	int nRet = 0;
	char buf[SIZE];
	FILE *fpr = NULL;
	FILE *fpw = NULL;

	if( (fpr=fopen("D:\\LED.hex", "r")) == NULL )
		fprintf(stderr, "Open LED.hex error");
	if( (fpw=fopen("D:\\test.hex", "w")) == NULL )
		fprintf(stderr, "Open test.hex error");

	while( (nRet=fread(buf, 1, sizeof(buf), fpr)) != 0 )
	{
		for(i=0; i<nRet; i++)
		{
			printf("%x ", buf[i]);
		}
		fwrite(buf, 1, nRet, fpw);
		++cnt;
	}
	printf("\nRead Times: %d, Down!\n", cnt);

	return 0;
}

fread(addr, size, num, fp); //size代表每次读取的字节数,num代表需要读取几块size这样的数据;

成功返回读取到的字节数,失败返回-1,读取到达文件末尾返回0;

实验发现,只要每次读一个字节,不管你buf的缓冲类型是什么,都是可以读取成功的,基本不会出现什么问题,这个东西熟悉C语言的应该都已经知道了,献丑了,下面的程序用来对比,nRet用来接收fread读到的字节数:

// Hex.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <string.h>

#define SIZE 256

int main(int argc, char* argv[])
{
	int i = 0;
	int cnt = 0;
	int nRet = 0;
	int flag = 1;
	short buf[SIZE];
	FILE *fpr = NULL;
	FILE *fpw = NULL;

	if( (fpr=fopen("D:\\LED.hex", "r")) == NULL )
		fprintf(stderr, "Open LED.hex error");
	if( (fpw=fopen("D:\\test.hex", "w")) == NULL )
		fprintf(stderr, "Open test.hex error");

	while( (nRet=fread(buf, 1, sizeof(buf), fpr)) != 0 )
	{
		if(flag == 1)
		{
			for(i=0; i<nRet; i++)
			{
				printf("%x ", buf[i]);
			}
		}
		fwrite(buf, 1, nRet, fpw);
		++cnt;
		++flag;
		memset(buf, 0, sizeof(buf));
	}
	printf("\nRead Times: %d, Down!\n", cnt);

	return 0;
}
注意,两种方式打印的格式不一样,因为第一个是char类型,第二个是short类型,但这里主要是验证文件是完好的,就不考虑这些了;



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值