二进制文件读取写入(一)
2015-12-08 14:55
295 查看
最近在老师推荐下,跟着田纳西大学James S. Plank的课程安排学习Unix Systems Programming
Lab链接在这里:
http://web.eecs.utk.edu/~plank/plank/classes/cs360/360/labs/lab2/index.html
在这里向和我一样没接触太多程序设计同学介绍一下学习过程:
5.9 二进制I/O
The functions from Section 5.6 operated with one character at a time, and the functions from Section 5.7 operated with one line at a time. If we’re doing binary I/O, we often would like to read or write an entire structure at a time. To do this using getc or putc, we have to loop through the entire structure, one byte at a time, reading or writing each byte. We can’t use the line-at-a-time functions, since fputs stops writing when it hits a null byte, and there might be null bytes within the structure. Similarly, fgets won’t work correctly on input if any of the data bytes are nulls or newlines. Therefore, the following two functions are provided for binary I/O.
运行结果
![](http://images.cnitblog.com/blog/372800/201410/281604566124225.png)
运行结果
Lab链接在这里:
http://web.eecs.utk.edu/~plank/plank/classes/cs360/360/labs/lab2/index.html
在这里向和我一样没接触太多程序设计同学介绍一下学习过程:
为什么使用二进制IO
引自:Advanced Programming in the UNIX Environment 3rd Edition5.9 二进制I/O
The functions from Section 5.6 operated with one character at a time, and the functions from Section 5.7 operated with one line at a time. If we’re doing binary I/O, we often would like to read or write an entire structure at a time. To do this using getc or putc, we have to loop through the entire structure, one byte at a time, reading or writing each byte. We can’t use the line-at-a-time functions, since fputs stops writing when it hits a null byte, and there might be null bytes within the structure. Similarly, fgets won’t work correctly on input if any of the data bytes are nulls or newlines. Therefore, the following two functions are provided for binary I/O.
函数原型
#include <stdio.h> size_t fread(void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp); size_t fwrite(const void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp); Both return: number of objects read or written
使用说明
unsigned char *str_buf; str_buf=(char *)malloc(sizeof(char)); *str_buf='a'; fwrite(str_buf,sizeof(char),5,fp);
运行结果
![](http://images.cnitblog.com/blog/372800/201410/281604566124225.png)
unsigned char *str_buf; str_buf=(unsigned char *)malloc(sizeof(unsigned char)); *str_buf='a'; int i; for(i=0;i<5;i++) fwrite(str_buf,sizeof(unsigned char),1,fp);
运行结果
![](http://images.cnitblog.com/blog/372800/201410/281608257697726.png)
相关文章推荐
- 关于理论、模型与算法
- log4j日志之xml形式
- 杭电2066 一个人的旅行(最短路)(floyd)
- iOS 简单实现重新获取验证码并倒计时60秒
- weblogic下载地址
- HDU 5592——ZYB's Premutation——————【线段树单点更新、单点查询】
- error C2039: “SetDefaultDllDirectories”: 不是“`global namespace'”的成员
- Oracle 的 rownum 问题
- .JsonParseException: Invalid UTF-8 start byte 0xb2
- 网络爬虫基本工作流程和抓取策略
- 《计算机图形学与几何造型导论》读书笔记1
- petaPar培训文档
- 等参元的高斯积分详解
- 水平集函数具体实现
- 分片实验的实现
- 自由表面处理,表面张力的实现
- 高等有限元中质量矩阵问题
- 扩展有限元中增强函数实例
- 光滑粒子流体动力学学习随笔
- 扩展有限元学习随笔