Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fwrite putting error indicator on stream in C

Tags:

c

In what cases does does the function fwrite put an error indicator onto the stream, such that ferror will return true?

Specifically, I am wondering if it puts an error when all the bytes were not successfully written.

Please provide a link as to where you get your information from.

Thank you

like image 988
Amandeep Grewal Avatar asked Feb 05 '26 08:02

Amandeep Grewal


1 Answers

If any error occurs, the error indicator for the stream will be set, and will not be cleared until clearerr is called. However, due to buffering, it's difficult for stdio functions to report errors. Often the error will not be seen until a later call, since buffering data never fails, but the subsequent write after the buffer is full might fail. If you're using stdio to write files, the only ways I know to handle write errors robustly are (choose one):

  • disable buffering (with setbuf or setvbuf - this must be the very first operation performed on the FILE after it's opened or otherwise it has UB)
  • keep track of the last successful fflush and assume any data after that might be only partially-written
  • treat any failed write as a completely unrecoverable file and just delete it

Also note that on a POSIX system, fwrite (and other stdio functions) are required to set errno to indicate the type of error, if an error occurs. As far as plain C is concerned, these functions may set errno, or they may not.

like image 127
R.. GitHub STOP HELPING ICE Avatar answered Feb 07 '26 21:02

R.. GitHub STOP HELPING ICE



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!