Search code examples
c++fileofstreamostream

What circumstances ostream::write or ostream::operator<< would fail under?


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?


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).