What circumstances ostream :: write or ostream :: operator << do not fall under?

In my C ++ code, I constantly write different values ​​to the file. My question is that if there are any circumstances that write or <will fail, given the fact that the file was successfully opened. Do I need to check every call to a record or <<to make sure it is executed correctly?

+4
source share
3 answers

Too many reasons for the failure to list them all. The following options are possible:

  • the section is finally filled
  • user exceeds his disk quota
  • the section was brutally unmounted
  • partition is corrupted (file system error)
  • the drive physically worked
  • ...

Do I need to check every call to a record or <<to make sure it is executed correctly?

If you want your program to be error-resistant, then definitely yes . If you do not, it simply means that the data you write may or may not be written, which means that you do not care.

Note. Instead of checking the status of the stream after each operation (which will be very tiring soon), you can set std::ostream::exceptions on you to like the stream to throw an exception when it fails (which should not be a problem, since such disk failures are by definition very exceptional).

+9
source

There are many reasons why a recording may fail. At the top of my head there are several:

  • The disk is full.
  • Disk failure
  • The file is on an NFS mount, and the network is disconnected.
  • The stream you write (remember that ostream is not always a file) turns out to be a channel that closes when a failure downstream
  • The stream you are writing is a TCP socket, and the peer is leaving.

And so on.

EDIT: I know that you said you were writing to a file, I just wanted to draw attention to the fact that your code should only care that it is written to ostream, which any stream could represent.

+7
source

Others examined situations that could lead to output failures.

But:

Do I need to check every call to a record or <<to make sure it is executed correctly?

For this, I would answer no. You might as well check

  • if the file was opened successfully, and
  • if the stream is still good() after you write your data.

It depends, of course, on the type of recorded data and the possibility / relative complexity of recovering from partial recording and restarting the application.

If you need more careful management when a write error has failed (for example, in order to make a graceful recovery), the associated exception stream associated with it is the way to go. The state of the poll stream after each operation will inflate the code.

+3
source

Source: https://habr.com/ru/post/1481296/


All Articles