EOF 是否设置错误号? [英] Does EOF set errno?
问题描述
我总是为系统调用的返回值而苦恼——它们太不一致了!通常我会检查它们是否为 NULL 或 -1,然后调用 perror
.但是,对于 fgets
,手册页说:
I always struggle with return values of system calls - they are just so inconsistent!
Normally I check if they are NULL or -1 and then call perror
. However, for fgets
, the man page says:
gets()
和 fgets()
成功时返回 s,错误时返回 NULL
或在没有字符的情况下出现文件结尾已阅读.
gets()
andfgets()
return s on success, andNULL
on error or when end of file occurs while no characters have been read.
这意味着返回值 NULL
不一定是错误 - 它也可以是 EOF.到达文件末尾时是否设置了 errno?在这种情况下,我还能调用 perror
吗?
which means the return value NULL
is not necessarily an error - it can also be EOF. Is errno set when the end of file is reached? Can I still call perror
in this case?
如果不是,判断调用是否返回错误与 EOF 的常用方法是什么.我想将 perror
与 NULL 字符串用于错误,并为 EOF 使用自定义字符串.
If not, what is the common way to tell if the call returned an error versus EOF. I want to use perror
with NULL string for errors and a custom string for EOF.
推荐答案
使用 ferror
和 feof
来区分错误和 EOF.没有通用的方法可以确切地找出错误是什么,如果有错误,但你可以知道有错误.
Use ferror
and feof
to distinguish between error and EOF. There's no general way to find out exactly what the error was, if there was an error, but you can tell that there was one.
标准 C (f)gets
(和 (f)getc
)不需要设置 errno
,尽管符合标准的库实现可以几乎可以随意将 errno
设置为非零值.
Standard C (f)gets
(and (f)getc
) are not required to set errno
, although a conforming library implementation can set errno
to a non-zero value pretty much at will.
Posix 确实要求 (f)get{c,s}
在读取错误时设置 errno
,但这只会在您确定存在读取错误后才能帮助您错误(通过调用 ferror
).同样重要的是要记住,库函数永远不会将 errno
设置为 0,但即使没有发生错误,也可以将 errno
设置为非零值.所以你不能测试 errno
来代替检查任何库函数的错误返回,包括 fgets
.由于文件尾不是错误,errno
将(可能)不会在 EOF 上被修改,因此在这种情况下它的值是没有意义的.
Posix does requires that (f)get{c,s}
set errno
on read errors, but that only helps you after you have determined that there was a read error (by calling ferror
). It's also important to remember that library functions never set errno
to 0, but may set errno
to a non-zero value even if no error occurs. So you cannot test errno
as a replacement for checking the error return of any library function, including fgets
. And since end-of-file is not an error, errno
will (probably) not be modified on EOF, so its value in that case is meaningless.
这篇关于EOF 是否设置错误号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!