从 fread() 失败中恢复的好方法是什么?
如果对 fread() 的调用返回 0 并且 Ferror() 指示错误(相对于 EOF),是否可以重试读取,或者最好关闭并重新打开文件?
我无法完全重新开始 - 输入文件已以无法撤消的方式部分处理(假设我一次向套接字写入一个块,并且由于现有协议,无法告诉远程端,“没关系,我需要重新开始”)。
我可以 fclose() 和 fopen() 文件,fseek() 过去已经处理的数据,然后从那里继续 fread(),但是这一切都是必要的吗?
If a call to fread() returns 0 and ferror() indicates an error (vs. EOF), is it OK to retry the read or is it better to close and reopen the file?
I can't start over entirely -- the input file has been partially processed in a way that can't be undone (say I'm writing out a chunk at a time to a socket and, due to existing protocol, have no way of telling the remote end, "never mind, I need to start over").
I could fclose() and fopen() the file, fseek() past the data already processed, and continue the fread()-ing from there, but is all that necessary?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不存在“一刀切”的解决方案,因为不同的错误可能需要不同的处理。 来自
fread()
的错误并不常见; 如果您正确调用它,则错误可能表示使FILE*
处于奇怪的错误状态的情况。 在这种情况下,您最好调用fclose()
、fopen()
、fseek()
以使事情恢复到良好状态。如果您正在为正在发生的事情进行编码,请提及您从
ferror()
收到的实际错误...There's no "one size fits all" solution, since different errors can require different handling. Errors from
fread()
are unusual; if you're calling it correctly, an error may indicate a situation that has left theFILE*
in a weird error state. In that case you're best off callingfclose()
,fopen()
,fseek()
to get things back in a good state.If you're coding for something that's happening, please mention the actual errors you're getting from
ferror()
...您可以查看
clearerr
函数。You can give the
clearerr
function a look.您可以使用
perror()
或strerror()
向用户显示错误,并询问她是否要重试。不过,实现提供这样的错误消息并不是强制性的。 在调用
fread()
之前,您应该将errno
设置为0; 如果失败并且 errno 仍然为 0,则不会有任何错误信息。You can show the error to the user with
perror()
orstrerror()
and ask her is she wants to retry.It's not mandatory for the implementation to provide such an error message, though. You should set
errno
to 0 before callingfread()
; if it fails anderrno
is still 0 then no error information will be available.