设为首页 加入收藏

TOP

C语言标准I/O_fread/fwrite
2015-01-21 11:08:31 】 浏览:1043
Tags:语言 标准 I/O_fread/fwrite


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

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

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

#include "stdafx.h"
#include 
  
   
#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
    
    

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 
     
      
#include 
      
        #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
       
        注意,两种方式打印的格式不一样,因为第一个是char类型,第二个是short类型,但这里主要是验证文件是完好的,就不考虑这些了;
        



】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Objective-C中可选参数的实现 下一篇C指针编程之道 ---第六次笔记

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目