二进制文件读取写入(一)

最近在老师推荐下,跟着田纳西大学James S. Plank的课程安排学习Unix Systems Programming

Lab链接在这里:
http://web.eecs.utk.edu/~plank/plank/classes/cs360/360/labs/lab2/index.html

在这里向和我一样没接触太多程序设计同学介绍一下学习过程:

为什么使用二进制IO

引自:Advanced Programming in the UNIX Environment 3rd Edition

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.

函数原型

#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);

运行结果

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);

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值