ç的fputc错误处理? [英] C fputc error handling?

查看:321
本文介绍了ç的fputc错误处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有的fputc使用大多数C文件写入示例的非常基本的例子与过程很少或没有错误检查。

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

我应结合使用什么错误检查技术和功能用的fputc循环,以确保的fputc已成功写入文件?我应该如何使用他们?

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?

我问的fputc原因是具体我使用的是双向链表的工作。

The reason I ask for fputc specifically is I am working with a doubly-linked list.

推荐答案

检查的fputc 的返回值通常不会告诉你任何用处,而且会让你的code狰狞。究其原因很少有意义的返回值是因为标准输入输出文件的缓存,然后写入错误(通常是由于耗尽磁盘空间,但它也可能是由于硬件故障而真的没有办法处理优雅)将不报告,直到缓冲区被刷新。正因为如此,它也不可能知道,甚至当一个报告错误,有多少已成功提交到磁盘。

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.

因此​​,我的观点是,你应该只使用标准输入输出写入文件,如果写入过程中发生任何错误时,你愿意考虑整个保存操作失败。如果采取这种方法,您可以完全忽略所有写函数的返回值。这是因为标准输入输出文件保持为访问内部错误指示器FERROR(F)。因此,只要做你写不检查任何错误,那么你关闭该文件之前,检查 FERROR(F)。如果它返回一个非零值,你知道你的保存操作失败,你可以报告给用户和删除部分写入文件。请记住,你应该先写一个临时文件,然后改名将此到位,而不是直接在你的旧文件上面写,除非你想冒险破坏用户的在失败的旧数据。

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.

这篇关于ç的fputc错误处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆