What events can cause ferror to return non-zero?

你。 提交于 2020-02-28 04:53:47

问题


What events can cause ferror() to return non-zero and after what events should one check ferror()?

http://www.cplusplus.com/reference/cstdio/ferror/

Opening, reading, closing?

Will the return value of ferror() ever change spontaneously? E.g., if a program checks ferror(stream), takes a nap without interacting with the FILE object associated with stream, and then checks ferror(stream) again, will the return value ever be different?

Is any of this mandated by standards?


回答1:


It is primarily errors returned from the underlying system calls (e.g. read, write, lseek, close) that will cause the stream's error bit to be set.

Many f___() functions from stdio.h indicate that if the end-of-file is reached, or an error occurs, ferror() or feof() will indicate why. fscanf, for example:

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 indicate the error.

Functions from stdio.h are synchronous - there's no background thread doing anything, so no, the error bit (returned from ferror()) will never spontaneously change. It will only be affected by a call to libc by your application.


For the very curious, one could clone the GLibc Git repository (git://sourceware.org/git/glibc.git) and have a look at the code itself.

ferror() essentially just checks for the _IO_ERR_SEEN bit in the file's _flags field. greping for that constant will show you all of the places it is set/cleared.



来源:https://stackoverflow.com/questions/27717132/what-events-can-cause-ferror-to-return-non-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!