Search code examples
c++c++11iostream

Check if a given ostream object has been written to


Can I query an ostream object about whether or not it has been written to? For an ostringstream, one could use

if(!myOssObject.str().empty())

What about the general case, e.g. an ofstream or cout or cerr?


Solution

  • In general No.

    You can find out how many char (or something else) is written before flushing (sending out the buffered data) by tellp():

    Returns the output position indicator of the current associated streambuf object.

    cout << "123";
    
    if (cout.tellp() > 0)
    {
        // There is some data written
    }
    

    After flushing, these output streams will forget what they've written but the last state flags.

    If the output device is a real-time and doesn't buffer anything, tellp can't help.