C语言标准I/O_fread/fwrite
来源:互联网 发布:mac桌面贴便签 编辑:程序博客网 时间:2024/05/18 20:50
好久不用,对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类型,但这里主要是验证文件是完好的,就不考虑这些了;
1 0
- C语言标准I/O_fread/fwrite
- C语言中的二进制I/O:fread、fwrite
- C语言标准I/O
- fwrite--C语言函数
- 理解C语言标准I/O函数
- C语言标准I/O文件操作
- C语言_标准I/O库
- C语言fwrite函数了解
- C语言fwrite函数了解
- C语言fwrite函数了解
- C标准IO的fread和fwrite
- 文件操作--标准I/O操作--fopen() fclose() fread() fwrite()
- APUE之标准I/O fopen,freopen,fread,fwrite实例。
- 标准I/O函数之fopen, fread, fwrite,fgetc,fputc
- C 语言标准 I/O 函数介绍以及演示程序
- C语言标准I/O函数及其特点总结
- 『C语言』标准I/O内幕
- C语言中的fread和fwrite
- 深入体验JavaWeb开发内幕——关于JEE中的response、resquest应答、请求头的编码问题的解决
- iOS--UIPikcerView的联动选择
- IOS开发---C语言-⑮结构体
- 一个好玩的黑客游戏
- iOS--UITableView的详细使用
- C语言标准I/O_fread/fwrite
- NYOJ 550 三位数逆序输出【水题】
- [poj1144 Network]tarjan求割点
- 大话工厂三剑客
- iOS--UITableView Grouped样式详细代码
- view的setTag() 和 getTag()应用
- 认真做人,努力做事情,我就是这样的程序员
- HDU 2795 Billboard
- 保留两位小数