博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

fread,fwrite

Posted on 2023-03-13 06:00  乔55  阅读(10)  评论(0编辑  收藏  举报

fread,fwrite

// fread,fwrite详解

// fread, fwrite - binary stream input/output
// 二进制流输入输出函数,在linux下不区分二进制流、文本流

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

// 功能描述:
// fread()  reads  nmemb  elements of data, each size bytes long, 
// from the stream pointed to by stream, 
// storing them at  the  loca‐tion given by ptr
// 从stream指向的流中读取nmen个数据,每个数据大小为size长度
// 将读取到的数据保存至ptr指向的空间内

// 返回值:
// On success, fread() and fwrite() return the number of items read or written
// If  an  error occurs,  or the end of the file is reached, 
// the return value is a short item count
// 成功,返回读取或写入的数据的个数(不是字节数,是对象的个数)
// 若发生错误,或者读取到了流的末尾,并未读取到nmenb个数据,
// 则返回实际读取到的数据,或者0。这是什么意思 ?

// 假设stream流中的数据量足够:
// 方式1:fread(buf,1,10,stream); 
// 读10个数据,每个数据1个字节,由于数据量足够,肯定读满10字节,返回值10
// 方式2:fread(buf,10,1,stream);
// 读1个数据,每个数据10个字节,数据量足够,返回值1

// 假设stream流中只有5个字节的数据:
// 方式1:fread(buf,1,10,stream); 
// 只读取到5个对象,返回值为5
// 方式2:fread(buf,10,1,stream);
// 想读取1个数据,但只有5个字节,不够1个对象,故返回值为0

// 总结:fread,fwirte使用单字节来使用更安全

size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);

// 功能描述:
// fwrite() writes nmemb elements of data, each size bytes long,
// to  the stream pointed to by stream, 
// obtaining them from the location given by ptr.
// 从ptr指向的空间中,获取nmenb个数据,每个数据大小为size长度
// 将获取到的数据写入stream指向的流中

fread,fwrite使用

// fread使用
// 形式1:
#define BUFSIZE 128
while(fread(buf,1,BUFSIZE,fps))
{
  fwrite(buf,1,BUFSIZE,fpd);
}
// 有问题。无法保证最后一次读操作时,刚好剩余128个对象让你去读取
// 应改为:
int n = 0;  // n记录实际读取到的数据数量 
while((n = fread(buf,1,BUFSIZE,fps)) > 0)
{
  fwrite(buf,1,n,fpd);  // 将实际读取到的数据量写入fpd
}