当前位置: 代码迷 >> 综合 >> C语言标准I/O_fread/fwrite
  详细解决方案

C语言标准I/O_fread/fwrite

热度:6   发布时间:2024-01-10 21:15:34.0


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

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

// Hex.cpp : Defines the entry point for the console application.
//#include "stdafx.h"
#include <stdio.h>
#define SIZE 512int 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 256int 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类型,但这里主要是验证文件是完好的,就不考虑这些了;