开发者

C fwrite error handling

When dealing with a count mismatch fr开发者_开发问答om fwrite (and therefore error), dealing with the error, what is the correct approach?

clearerr(File); //Clear the error
fflush(File); //Empty the buffer of it's contents

Or:

fflush(File); //Other way around, empty buffer first then reset
clearerr(File);

Or just:

clearerr(File); //Contains fflush implicitly?

Or something else?


There isn't really anything you can do if you encounter a write error. You can flush the buffer, but your last write was still broken, so the file doesn't contain what you want. You could close the file, reopen it for writing (with "truncate") and write it anew, but that only works if you still have the entire file content in memory.

Alternatively, you could reopen and see how much data has been written, but that doesn't help you if there's an external reason why you can't write to the file, so there's really no graceful way to recover.

So in short, you don't "handle" the error at the file site; rather, your program must handle the larger error condition that the write just failed and react at an appropriate point.

You should probably consider "atomic writes", which means you first write your file to a temporary, and only if you succeed to you delete the original and rename the temporary to the original file name. That way the file itself is always in a consistent state.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜