Question

In my C++ code, I am constantly writing different values into a file. My question is that if there is any circumstances that write or << would fail under, considering the fact that file was opened successfully. Do I need to check every single call of write or << to make sure it was carried out correctly?

Was it helpful?

Solution

There are too many failure reasons to list them all. Possible ones would be:

  • the partition is finally full
  • the user exceeds his disk quota
  • the partition has been brutally unmounted
  • the partition has been damaged (filesystem bug)
  • the disk failed physically
  • ...

Do I need to check every single call of write or << to make sure it was carried out correctly?

If you want your program to be resilient to failures then, definitely, yes. If you don't, it simply means the data you are writing may or may not be written, which amounts to say you don't care about it.

Note: Rather than checking the stream state after every operation (which will soon be extremely tedious) you can set std::ostream::exceptions to your liking so that the stream will throw an exception when it fails (which shouldn't be a problem since such disk failures are quite exceptional by definition).

OTHER TIPS

There are any number of reasons why a write could fail. Off the top of my head here are a few:

  1. The disk is full
  2. The disk fails
  3. The file is on an NFS mount and the network goes down
  4. The stream you're writing to (remember that an ostream isn't always a file) happens to be a pipe that closes when the downstream reader crashes
  5. The stream you're writing to is a TCP socket and the peer goes away

And so on.

EDIT: I know you've said that you're writing to a file, I just wanted to draw attention to the fact that your code should only care that it's writing to an ostream which could represent any kind of stream.

The others covered situations that might result in output failure.

But:

Do I need to check every single call of write or << to make sure it was carried out correctly?

To this, I would answer "no". You could conceivably just as well check

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

This depends, of course, on the type of data written, and the possibility / relative complexity of recovering from partial writes vs. re-running the application.

If you need closer control on when exactly a write failed (e.g. in order to do a graceful recovery), the ostream exceptions syam linked to are the way to go. Polling stream state after each operation would bloat the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top