码迷,mamicode.com
首页 > 编程语言 > 详细

C语言标准I/O_fread/fwrite

时间:2014-12-09 19:39:08      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   sp   for   on   文件   数据   


好久不用,对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类型,但这里主要是验证文件是完好的,就不考虑这些了;



C语言标准I/O_fread/fwrite

标签:style   blog   io   ar   sp   for   on   文件   数据   

原文地址:http://blog.csdn.net/scottly1/article/details/41593463

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!