Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for success of fwrite in C, perror

Tags:

c

fwrite

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.

like image 911
Crystal Avatar asked Feb 24 '10 21:02

Crystal


People also ask

How do I know if fwrite was successful?

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.

How do I know if fwrite is failing?

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.

How do you know if Fread fails?

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.

What does fwrite function return?

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.


1 Answers

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 the fwrite(3) system call. The least the message will contain is the value of strerror(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.

like image 74
M.S. Dousti Avatar answered Sep 17 '22 01:09

M.S. Dousti