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

Check if a given ostream object has been written to

本文关键字:ostream 对象 是否 检查      更新时间:2023-10-16

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

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

一般情况,例如ofstreamcoutcerr呢?

一般没有。

您可以通过以下方式找出在刷新(发送缓冲数据)之前写入了多少字符(或其他内容tellp()

返回当前关联值的输出位置指示器 流布夫对象。

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

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

如果输出设备是实时的并且不缓冲任何内容,则tellp无济于事。

这是可能的,但前提是你能得到你的手事先。 唯一通常保证的解决方案是插入一个过滤流,它跟踪字符输出:

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( nullptr )
        , myCharCount( 0 )
    {
    }
    CountOutput( std::ostream& dest )
        : myDest( dest.rdbuf() )
        , myOwner( &dest )
        , myCharCount( 0 )
    {
        myOwner->rdbuf( this );
    }
    ~CountOutput()
    {
        if ( myOwner != nullptr ) {
            myOwner.rdbuf( myDest );
        }
    }
    int count() const
    {
        return myCount;
    }
};

像往常一样,这几乎可以与任何std::ostream一起使用:

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

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