I’m working on some code that generates a lot of
ignoring return value of ‘size_t fwrite(const void*, size_t, size_t, FILE*)’, declared with attribute warn_unused_result
warnings when compiled with g++, and I’m wondering about the best programming pattern to actually record and handle the return value of a large number of separate sequential fwrites (i.e. not the same fwrite in a loop)
Let’s say that the code looks like this at the moment:
fwrite (&blah, sizeof (blah), 1, fp); // ... more code ... fwrite (&foo, sizeof (foo), 1, fp); // ... more code ...
I’m currently thinking about something like this, but I may have difficulty cleaning up the file pointer:
if (fwrite (&blah, sizeof (blah), 1, fp) != 1) return someerrorcode; // ... more code ... if (fwrite (&foo, sizeof (foo), 1, fp) != 1) return someerrorcode; // ... more code ...
I think that approach is clearly better than nesting, which would get too crazy too quick:
if (fwrite (&blah, sizeof (blah), 1, fp) == 1) { // ... more code ... if (fwrite (&foo, sizeof (foo), 1, fp) == 1) {; // ... more code ... } }
Surely there is already an established best-practice pattern for this sort of thing, though?
Of course, as I am mainly looking into this to get rid of the compiler warnings, I could just assign the return value to a dummy variable and ignore it, but I’d like to try doing it the right way first.
dummy = fwrite (&blah, sizeof (blah), 1, fp); // ... more code ... dummy = fwrite (&foo, sizeof (foo), 1, fp); // ... more code ...
Update: I’ve removed the c++ tag as this code is really just c being compiled using g++, so c based solutions are needed to keep with the rest of the code base.
I’d do something along these lines:
With a little C99 macro magic
and using
ferror()instead of our own error flag as suggested by Jonathan Leffler, this can be written asIf there are other error conditions aside from io errors, you’ll still have to track them with one or more error variables, though.
Also, your check againstsizeof(blah)is wrong:fwrite()returns the count of objects written!