什么是FREAD / FWRITE回吐大小和数量作为参数的原因是什么? [英] What is the rationale for fread/fwrite taking size and count as arguments?

查看:170
本文介绍了什么是FREAD / FWRITE回吐大小和数量作为参数的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个在工作中对为什么FREAD和fwrite采取每件的大小和数量,并返回的成员数读/写,而不是仅仅采取缓冲区和大小在这里讨论。它唯一的用途,我们可以拿出来说,如果你想读/写结构不属于该平台定位整除,因此已填充的数组但不能是如此普遍,以保证这种选择在设计上。

从的 FREAD(3)的:


  

函数fread()读取数据nmemb个元素,每个大小字节长,
  从流指向的流,在给定的位置将它们存储
  由ptr。


  
  

函数fwrite()将写入nmemb个数据元素,每个大小字节
  长,到流指向的数据流,来自位置获得它们
  由ptr给出。


  
  

的fread()和fwrite()返回的项数成功读取或写入
  (即,不将字符数)。如果发生错误,或
  档案结尾到达,返回值是一个简短的项目数(或零)。



解决方案

这是基于怎样的 FREAD 实施

统一UNIX规范说:


  

有关的每个对象,大小呼叫应
  向龟etc()函数和制成
  结果存储在顺序读取,在
  unsigned char型的数组确切
  覆盖的对象。


龟etc 也有这样的提示:


  

由于龟etc()上的字节进行操作,
  读取组成的字符
  多个字节(或多字节
  字符)可能需要多个呼叫
  到龟etc()。


当然,这predates看中可变字节字符编码如UTF-8。

该SUS指出,这实际上是从ISO C文件拍摄。

We had a discussion here at work regarding why fread and fwrite take a size per member and count and return the number of members read/written rather than just taking a buffer and size. The only use for it we could come up with is if you want to read/write an array of structs which aren't evenly divisible by the platform alignment and hence have been padded but that can't be so common as to warrant this choice in design.

From FREAD(3):

The function fread() reads nmemb elements of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.

The function 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.

fread() and fwrite() return the number of items successfully read or written (i.e., not the number of characters). If an error occurs, or the end-of-file is reached, the return value is a short item count (or zero).

解决方案

It's based on how fread is implemented.

The Single UNIX Specification says

For each object, size calls shall be made to the fgetc() function and the results stored, in the order read, in an array of unsigned char exactly overlaying the object.

fgetc also has this note:

Since fgetc() operates on bytes, reading a character consisting of multiple bytes (or "a multi-byte character") may require multiple calls to fgetc().

Of course, this predates fancy variable-byte character encodings like UTF-8.

The SUS notes that this is actually taken from the ISO C documents.

这篇关于什么是FREAD / FWRITE回吐大小和数量作为参数的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆