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

来源:互联网 发布:linux 查看系统信息 编辑:程序博客网 时间:2024/06/07 02:09

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

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

原创粉丝点击