开发者

C fputc error handling?

开发者 https://www.devze.com 2023-04-05 12:06 出处:网络
Most C file writing examples for fputc use a very basic example with little or no error checking of the process.

Most C file writing examples for fputc use a very basic example with little or no error checking of the process.

What error-checking te开发者_如何学Cchniques 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 fputc will 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 FILE keeps an internal error indicator accessible as ferror(f). So just do all your writes without checking for any errors, then before you close the file, check ferror(f). If it returns a nonzero value, you know your "save" operation failed, and you can report this to the user and remove the partially-written file. Keep in mind you should be writing first to a temporary file then rename this 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.


You should check the int return value from fputc(). The following is a list:

On success, fputc() returns the value c that it wrote to stream. On failure, it returns EOF and sets errno to one of the following values:

EACCES

Another process has the file locked. 

EBADF

stream is not a valid stream opened for writing. 

EFBIG

The file is a regular file and an attempt was made to write at or

beyond the offset maximum.

EINTR

A signal interrupted the call. 

EIO

An output error occurred. 

ENOMEM

Memory could not be allocated for internal buffers. 

ENOSPC

An attempt is made to write to a full disk.

ENXIO

A device error occurred. 

EPIPE

An attempt is made to write to a closed pipe.
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号