With fwrite returning the number of successful elements written to the file, by saying:
if (!(fwrite(...))) {
fprintf(stderr, "Failure");
//perror(???) I sometimes see code that says perror here and I don't know
//exactly what this does.
}
Does this check for successful writing to the file? Are there other things to worry about?
Thanks.
The fwrite() function returns the number of members successfully written, which may be less than nitems if a write error is encountered. If size or nitems is 0, fwrite() returns 0 and the state of the stream remains unchanged.
For fwrite, on a short write (where less than your entire data was written) you can check feof() and/or ferror() to see if the stream is returning and end-of-file, EOF, such as if a PIPE was closed, or if the stream has its error inducator flag set.
If fread returns fewer than the requested number of records, you've either hit EOF or a serious read error. You can distinguish between them by checking feof() and ferror() . Similarly, if fwrite returns fewer than the requested number of records, you've either run out of disk space or hit a serious write error.
The fwrite() function writes up to count items, each of size bytes in length, from buffer to the output stream . Return Value. The fwrite() function returns the number of full items successfully written, which can be fewer than count if an error occurs.
You can also use explain_fwrite()
, explain_errno_fwrite
, ... from libexplain
.
The man page explains:
The
explain_fwrite
function is used to obtain an explanation of an error returned by thefwrite(3)
system call. The least the message will contain is the value ofstrerror(errno)
, but usually it will do much better, and indicate the underlying cause in more detail.The errno global variable will be used to obtain the error value to be decoded.
This function is intended to be used in a fashion similar to the following example (the man-page was wrong here, as correctly pointed out by @puchu in the comment below. I corrected the code to address the issue):
if (fwrite(ptr, size, nmemb, fp) < nmemb) { fprintf(stderr, "%s\n", explain_fwrite(ptr, size, nmemb, fp)); exit(EXIT_FAILURE); }
Caveat: This method is not thread-safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With