Do ferrors carry through multiple writes?

70 views Asked by At

Does the ferror in this example check check both fprintfs for error, or just the second one?

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);
}
1

There are 1 answers

4
Jean-François Fabre On BEST ANSWER

If an error occurs, it won't be reset unless clearerr is called on your stream, so yes, an error occuring on any of both writes is recorded.

from 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.

But you could also simply use fprintf return code to see if something went wrong:

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

(fprintf manual page)

Like this (Thanks Jonathan for pointing out the errors in the original 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!");