Check if this ostream object has been written to

Is it possible to query an object ostreamabout whether it was recorded? For ostringstreamcan use

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

How about a general case, for example. a ofstreamor coutor cerr?

+4
source share
2 answers

General No.

You can find out how much char (or something else) was written before flushing (sending buffered data) tellp():

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

cout << "123";

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

After flushing, these output streams will forget what they wrote, but the last status flags.

, tellp .

+5

, . streambuf, :

class CountOutput : public std::streambuf
{
    std::streambuf* myDest;
    std::ostream*   myOwner;
    int myCharCount;    //  But a larger type might be necessary

protected:
    virtual int overflow( int ch )
    {
        ++ myCharCount;
        return myDest->sputc( ch );
    }

public:
    CountOutput( std::streambuf* dest )
        : myDest( dest )
        , myOwner( NULL )
        , myCharCount( 0 )
    {
    }
    CountOutput( std::ostream& dest )
        : myDest( dest.rdbuf() )
        , myOwner( &dest )
        , myCharCount( 0 )
    {
        myOwner->rdbuf( this );
    }
    ~CountOutput()
    {
        if ( myOwner != NULL ) {
            myOwner.rdbuf( myDest );
        }
    }

    int count() const
    {
        return myCount;
    }
};

, std::ostream:

CountOutput counter( someOStream );
//  output counted here...
int outputCount = counter.count();

, .

+3

All Articles