cullub cullub - 4 days ago 7
C Question

Do ferrors carry through multiple writes?

Do I have to check for an error after each write, or can I wait until the end?

For example,

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


Does the
ferror
check check both
fprintf
s for error, or just the second one?

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