Ferror 是否会进行多次写入?

Do ferrors carry through multiple writes?

此示例中的 ferror 检查是检查两个 fprintf 是否有错误,还是只检查第二个?

FILE * myout;
if ((myout = fopen("Assignment 11.txt", "a")) != NULL)
{
    fprintf(myout, "First print ", str1);  
    fprintf(myout, "Second print", str1);

    if (ferror(myout))
        fprintf(stderr, "Error printing to file!");

    fclose(myout);
}

如果发生错误,除非在您的流上调用 clearerr,否则它不会被重置,所以是的,两次写入中的任何一次发生的错误都会被记录下来。

来自 ferror manual page:

The function ferror() tests the error indicator for the stream pointed to by stream, returning nonzero if it is set. The error indicator can only be reset by the clearerr() function.

但您也可以简单地使用 fprintf return 代码来查看是否出现问题:

If an output error is encountered, a negative value is returned.

(fprintf manual page)

像这样(感谢Jonathan指出原文中的错误post):

if (fprintf(myout, "First print %s\n", str1)<0) fprintf(stderr, "Error printing to file #1!");
if (fprintf(myout, "Second print %s\n", str1)<0) fprintf(stderr, "Error printing to file #2!");