Most C file writing examples for fputc use a very basic example with little or no error checking of the process.
What error-checking techniques and functions should I use in conjunction with a fputc loop to ensure that fputc has successfully written to file? And how should I use them?
The reason I ask for fputc specifically is I am working with a doubly-linked list.
Checking the return value of
fputcwill usually not tell you anything useful, and will make your code hideous. The reason the return value of rarely meaningful is because stdio files are buffered, and a write error (usually due to exhausting disk space, but it could also be due to hardware failure which there’s really no way to handle gracefully) will not be reported until the buffer is flushed. Because of this, it’s also impossible to know, even when an error is reported, how much was successfully committed to disk.As such, my view is that you should only use stdio to write files when you’re willing to consider the entire “save” operation a failure if any error occurs during writing. If you take this approach, you can completely ignore the return value of all write functions. This is because the stdio
FILEkeeps an internal error indicator accessible asferror(f). So just do all your writes without checking for any errors, then before you close the file, checkferror(f). If it returns a nonzero value, you know your “save” operation failed, and you can report this to the user andremovethe partially-written file. Keep in mind you should be writing first to a temporary file thenrenamethis into place, rather than writing directly over top of your old file, unless you want to risk destroying the user’s old data on failure.