这么好的人!
我有一个理论上的问题。在read()手册中,我阅读了以下内容:
On error, -1 is returned, and errno is set appropriately. In this
case, it is left unspecified whether the file position (if any)
changes.在fread()中,对应的片段如下:
If an error occurs, or the end of the file is
reached, the return value is a short item count (or zero).
...
**fread()** does not distinguish between end-of-file and error, and
callers must use feof(3) and ferror(3) to determine which occurred.我的问题-- read()为什么会区分EOF和错误,而fread()不区分,有什么实际原因吗?
提前谢谢你!
发布于 2020-08-27 18:18:47
fread的返回值为size_t。这是一种无符号类型,因此没有与指示读取多少项的值不同的可用值。
此外,fread()可能需要多次调用read()来读取所请求的所有项。如果在后一次读取时发生错误或EOF,则仍应返回在此之前成功读取的所有项。所以它会返回项目计数。
由于短项计数的原因不能在返回值中编码,因此需要有其他方法来返回这个值。让调用者使用feof()和ferror()就更容易了。
如果read()在部分读取后遇到错误,这通常被视为成功。它返回读取的数据的长度。调用者直到下一次调用read()时才会发现错误,然后返回-1并设置errno。
信号也会导致read()提前返回。在本例中,它返回-1并设置errno == EINTR。内核将部分读取保存在缓冲区中,以便在下一次调用时返回。
https://stackoverflow.com/questions/63621827
复制相似问题