1
votes

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
I would think you would want to check after each write so that you know exactly when an error occurred.Michael Dorgan
@Michael Yes, maybe, in a perfect world :) But currently, I'm printing two times right next to each other; basically two parts of the same line of text. I don't really care which one makes the error, I just need to know whether any errors occurred.Cullub

1 Answers

2
votes

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!");