遇到这种C语言函数/系统调用/过程调用的问题的时候,就在shell里man一下,仔细读读Linux Mannual。
比如说这个问题,man 3 scanf
然后输入/return
然后就会看到这么一段话:
On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.
The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the
error indicator for the stream (see ferror(3)) is set, and errno is set to indicate the error.
你就知道啊原来读到结尾或者read出错就会返回EOF。那么什么时候read会出错呢?
我们知道C语言中具体的错误类型通常由一个线程局部变量errno标识,manual里面也会对库函数可能引发的错误作阐述。
然后你可以看看下面的errno的描述:
ERRORS
EAGAIN The file descriptor underlying stream is marked nonblocking, and the read operation would block.
EBADF The file descriptor underlying stream is invalid, or not open for reading.
EILSEQ Input byte sequence does not form a valid character.
EINTR The read operation was interrupted by a signal; see signal(7).
EINVAL Not enough arguments; or format is NULL.
ENOMEM Out of memory.
ERANGE The result of an integer conversion would exceed the size that can be stored in the corresponding integer type.
你大概心里对哪些情况scanf会出错应该就有点想法了吧?