fwrite将错误指示符放在C中的流上
在什么情况下,函数fwrite将错误指示符放到流上,这样ferror将返回true?
具体来说,我想知道如果没有成功写入所有字节,它是否会出错。
请提供您从何处获取信息的链接。
谢谢
如果发生任何错误,将设置流的错误指示符,并且在调用clearerr
之前不会清除该错误指示符。 但是,由于缓冲,stdio函数很难报告错误。 通常直到稍后调用才会看到错误,因为缓冲数据永远不会失败,但缓冲区已满后的后续写入可能会失败。 如果您使用stdio来编写文件,我知道的唯一可靠的方法就是(选择一个):
- 禁用缓冲(使用
setbuf
或setvbuf
– 这必须是在FILE
打开后在FILE
上执行的第一个操作,否则它具有UB) - 跟踪上次成功的
fflush
并假设之后的任何数据可能只是部分写入 - 将任何失败的写入视为完全不可恢复的文件,然后将其删除
另请注意,在POSIX系统上,如果发生错误,则需要fwrite
(和其他stdio函数)来设置errno
以指示错误类型。 就普通C而言,这些function可能设置为errno
,或者它们可能不设置。
从我的Linux系统上的fwrite手册页:
RETURN VALUE fread() and fwrite() return the number of items successfully read or written (ie, not the number of characters). If an error occurs, or the end-of-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.
只是阅读手册页,它看起来不会设置errno
。