Search code examples
c++error-handlingerror-checking

How can I error check a stream read or write in C++?


In C, we can check the return value of printf(), fwrite(), fread(), etc. to tell if it succeeded or not.

int main(void) {
    if (printf("Hello world!\n") < 0)
        abort();
    return 0;
}

But in C++, how can I tell if the following succeeded or not?

std::cout << "Hello world!" << std::endl;

Solution

  • The stream itself has a conversion to boolean that tells you whether it's in a failed state or not:

    if (!(std::cout << "Hello World!" << std::endl)) {
        std::cerr << "Write to cout failed\n";
    }
    

    Of course, if writing to cout fails, there's a pretty decent chance that writing to cerr will also fail, so this doesn't necessarily make a lot of sense, but hopefully you get the general idea anyway.

    One other note: the failed state is persistent, so checking this tells you whether the stream has failed at some time in the past, but (unless you check every time) you don't necessarily know whether it was the most recent attempt at writing that failed, or some previous attempt. You can clear the failed state with the stream's clear() method when needed, ie to recover from a failure, for example.