在 fread(3) 中检查读取的项目数是否小于请求数而不是 0 是否正确?

Is it correct to check if the number of items read is less than requested, rather than 0, in fread(3)?

我是 C 的初学者。我想知道检查 fread(3) 的 return 值(即读取的项目数)是否小于请求的数量是否正确,而不仅仅是 0,来检测 EOF。例如,假设您有

#include <stdio.h>

int main(void)
{
    unsigned char buffer[1024];

    while (fread(buffer, 1, sizeof(buffer), stdin) == sizeof(buffer))
    {
        printf("%s\n", "Not EOF yet");
    }

    printf("%s\n", "At EOF");

    return 0;
}

这是正确的吗? == sizeof(buffer) 的检查应该改为 != 0 吗? fread 是否允许部分填充缓冲区?

我问的原因:看来read可能return小于sizeof(buffer)。引用联机帮助页:

On success, the number of bytes read is returned (zero indicates end of file), and the file position is advanced by this number. It is not an error if this number is smaller than the number of bytes requested; this may happen for example because fewer bytes are actually available right now (maybe because we were close to end-of-file, or because we are reading from a pipe, or from a ter- minal), or because read() was interrupted by a signal.

然而,出于某种原因,相同的逻辑似乎不适用于 fread

On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).

所以我想确认支票确实应该是 == sizeof(buffer) 而不是 != 0

感谢您的帮助!

您引用的手册部分说:

If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).

这意味着您不能使用 !=0 检查是否没有发生错误,因为 fread() 可以 return 一个短项目计数。

fread() 的手册页还指出:

fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.

所以 如果 项目数 returned 少于要求,那么你必须使用 feof()ferror() 来计算发生了哪一个(如果它是文件结尾,那么您可以得出结论,这不是输入错误,而是您正在读取的任何流的输入结束)。