unix环境高级编程-5.9-二进制I/O

上一节,我们知道对于读或者写都是一个一个字节,或者一行行的。

getc和putc是通过字节来处理。fputs和fgets是一行的,但是遇到null就停止了。

下面介绍fread和fwrite函数

原型:

#include<stdio.h>

size_t fread(void* restrict ptr,size_t size,size_t nobj,FILE* restrict fp);

size_t fwrite(void* restrict ptr,size_t size,size_t nobj,FILE* restrict fp);

返回值为读或者写的对象数。

 


size_t fread (void *data, size t size, size t count, FILE *stream) [Function]
This function reads up to count objects of size size into the array data, from the
stream stream. It returns the number of objects actually read, which might be less
than count if a read error occurs or the end of the file is reached. This function
returns a value of zero (and doesn’t read anything) if either size or count is zero.
If fread encounters end of file in the middle of an object, it returns the number of
complete objects read, and discards the partial object. Therefore, the stream remains
at the actual end of the file.

 

size_t fwrite (const void *data, size t size, size t count, FILE [Function]
*stream)
This function writes up to count objects of size size from the array data, to the
stream stream. The return value is normally count, if the call succeeds. Any other
value indicates some sort of error, such as running out of space.

 

例子

读或者写一个二进制数组。

floate data[10];

if(fwrite(&data[2],size(floate),4,fp)!=4)

err_sys("error);


 

读或者写一个结构体。

struct{
	short count;
	long total;
	char name[NAMESIZE];
}item;

if(fwrite(&item,sizeof(item),1,fp)!=1)
	err_sys("error");


 

nobj为要读取的元素个数

 

上边两个函数返回值都为读写对象数。如果出错或者到达尾端。则此数字可以少于nobj,所以要用函数ferror和feof判断什么情况。但对于写。返回值少于nobj值,就出错。

目前在不同的系统等,会出现不一样的。

 

 

原因如下。

同一个结构同一成员,偏移量可能因编译器和系统而不同。

用于存储多个字节整数和浮点值的二进制村饭方式也可能因编译器选线不同而不同。

更多文章,欢迎访问http://blog.csdn.net/wallwind

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值