检查是否已写入给定的ostream对象

时间:2013-10-15 10:00:12

标签: c++ c++11 iostream

我是否可以查询ostream对象是否已写入?对于ostringstream,可以使用

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

一般情况如何,例如ofstreamcoutcerr

2 个答案:

答案 0 :(得分:5)

一般情况下编号

您可以通过tellp()找出在刷新(发送缓冲数据)之前写入多少个char(或其他内容):

  

返回当前关联的输出位置指示符   streambuf对象。

cout << "123";

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

刷新后,这些输出流将忘记他们写的内容但是最后的状态标志。

如果输出设备是实时的并且没有缓冲任何内容,tellp无法帮助。

答案 1 :(得分:3)

这是可能的,但前提是你可以把手放在溪边 预先。唯一通常保证的解决方案是插入 过滤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();

当它超出范围时,它将恢复原始状态 流。