Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to recover from a fread() failure?

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?

like image 374
Dan Avatar asked Oct 20 '25 14:10

Dan


2 Answers

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 the FILE* in a weird error state. In that case you're best off calling fclose(), 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()...

like image 127
dwc Avatar answered Oct 22 '25 02:10

dwc


You can give the clearerr function a look.

like image 44
dirkgently Avatar answered Oct 22 '25 03:10

dirkgently



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!