检查是否已写入给定的 ostream 对象
Check if a given ostream object has been written to
我可以查询ostream
对象是否已写入吗?对于ostringstream
,可以使用
if(!myOssObject.str().empty())
一般情况,例如ofstream
或cout
或cerr
呢?
一般没有。
您可以通过以下方式找出在刷新(发送缓冲数据)之前写入了多少字符(或其他内容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();
当它超出范围时,它将恢复原始状态流。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 为什么重载运算符上的异常说明符'<<'不适用于任何 std::ostream 对象,但对库中定义的运算符不起作用?
- C++ ostream 从对象数组返回数据
- 如何跟踪写入std :: Ostream对象的字节数
- 使用 std::ostream 方法将格式化文本输出到 std::string 对象
- 如何获取您放入 ostream 对象中的最后一个字符
- 检查是否已写入给定的 ostream 对象
- 使用指针数组中的对象调用重载的友元 ostream 插入运算符将返回内存地址
- 重载 std::ostream 运算符<<未调用,stream 获取变量地址而不是对象
- 使用boost::python时,将python.io对象转换为std::ostream
- 对象文件中的ostream操作符发生了什么?
- 为什么即使我没有使用 ostream 对象,ostream 的 put 指针也会被修改
- 如何传递ostream对象
- 我可以使用FILE*来初始化c++ ostream对象吗?
- 关于临时ostream对象的c++问题
- 子对象的Ostream获取父对象的Ostream