fread/fwrite 将大小和计数作为参数的基本原理是什么? [英] What is the rationale for fread/fwrite taking size and count as arguments?

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

问题描述

我们在这里讨论了为什么 fread()fwrite() 为每个成员指定一个大小并计算并返回读取/写入的成员数量而不是不仅仅是获取缓冲区和大小.我们可以想出的唯一用途是,如果您想读/写一个结构数组,这些结构不能被平台对齐整除,因此已被填充,但不能如此普遍以保证这种选择在设计中.

来自fread(3):

<块引用>

函数 fread() 读取 nmemb 元素的数据,每个 size 字节长,从流指向的流中,将它们存储在给定的位置作者:

<块引用>

函数 fwrite() 写入 nmemb 元素的数据,每个 size 字节long,到stream指向的stream,从location获取由ptr给出.

<块引用>

fread() 和 fwrite() 返回成功读取或写入的项目数(即,不是字符数).如果发生错误,或到达文件尾,返回值是一个短的项目计数(或零).

解决方案

它基于 fread 已实现.

单一 UNIX 规范说

<块引用>

对于每个对象,大小调用应为对 fgetc() 函数和结果按读取顺序存储在一个完全无符号字符的数组覆盖对象.

fgetc 也有这个注释:

<块引用>

由于 fgetc() 对字节进行操作,读取一个字符组成的多个字节(或一个多字节字符") 可能需要多次调用到 fgetc().

当然,这早于像 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 structures 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天全站免登陆