2011-04-21 86 views
4

我正在使用std :: ofstream作为跟踪输出。dupplicating std :: ofstream附加内容

由于某些原因,我有时候想把我在std :: ofstream(不刷新或关闭)末尾追加的内容复制到另一个std :: ofstream中;

您是否想过实现这一目标的方法?

THX

+1

目前我正在重新考虑我的问题。我使用临时std :: stringstream,我将其添加到流或根据需要dupplicate它们。它可以完成这项工作。 – 2011-04-21 13:25:11

+0

是的,我想过这个。我只是想写它(但我不知道是否有更好的方法,并放弃回答:D +1 – 2011-04-21 13:26:32

+0

我试过了,但rdbuf不能设置forstream;我不知道它会工作无论如何 – sehe 2011-04-21 13:35:30

回答

7

Boost.IostreamsTee过滤器可以输出流分成两个。

下面是一个例子,其中Johannes Schaub在他的回答here中给出了很大的启发。

#include <sstream> 
#include <iostream> 
#include <boost/iostreams/stream.hpp> 
#include <boost/iostreams/tee.hpp> 

int main() 
{ 
    namespace io = boost::iostreams; 
    typedef io::tee_device<std::ostream, std::stringstream> TeeDevice; 
    typedef io::stream<TeeDevice> TeeStream; 
    std::stringstream ss; 
    TeeDevice teeDevice(std::cout, ss); 
    TeeStream tee(teeDevice); 
    tee << "Hello World\n" << std::flush; 
    std::cout << "ss: " << ss.str() << "\n"; 
} 

当我省略冲洗机械手时,ss.str()返回一个空字符串。我不知道这是否是预期的行为。

+0

是的, stringstream会被[缓冲](http://www.cplusplus.com/reference/iostream/stringstream/),缓冲区写在['flush]之后(http:// www .cplusplus.com/reference/iostream/ostream/flush /)。'endl'也会刷新流。 – Christian 2012-04-15 14:26:19