我想将两个(或更多)流组合成一个流。我的目标是将任何定向到cout
、cerr
和clog
的输出与原始流一起输出到一个文件中。(例如,当某些内容被记录到控制台时。关闭后,我希望仍然能够返回并查看输出。)
我在考虑做这样的事情:
class stream_compose : public streambuf, private boost::noncopyable
{
public:
// take two streams, save them in stream_holder,
// this set their buffers to `this`.
stream_compose;
// implement the streambuf interface, routing to both
// ...
private:
// saves the streambuf of an ios class,
// upon destruction restores it, provides
// accessor to saved stream
class stream_holder;
stream_holder mStreamA;
stream_holder mStreamB;
};
这看起来足够直接了。然后,main中的调用将类似于:
// anything that goes to cout goes to both cout and the file
stream_compose coutToFile(std::cout, theFile);
// and so on
我还查看了boost::iostreams
,但没有看到任何相关内容。
有没有其他更好/更简单的方法来实现这一点?
发布于 2009-11-19 22:03:31
您提到在Boost.IOStreams中没有找到任何东西。您是否考虑过tee_device
发布于 2009-11-19 13:13:46
我会编写一个自定义的流缓冲区,它只是将数据转发到所有链接的流的缓冲区。
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <functional>
class ComposeStream: public std::ostream
{
struct ComposeBuffer: public std::streambuf
{
void addBuffer(std::streambuf* buf)
{
bufs.push_back(buf);
}
virtual int overflow(int c)
{
std::for_each(bufs.begin(),bufs.end(),std::bind2nd(std::mem_fun(&std::streambuf::sputc),c));
return c;
}
private:
std::vector<std::streambuf*> bufs;
};
ComposeBuffer myBuffer;
public:
ComposeStream()
:std::ostream(NULL)
{
std::ostream::rdbuf(&myBuffer);
}
void linkStream(std::ostream& out)
{
out.flush();
myBuffer.addBuffer(out.rdbuf());
}
};
int main()
{
ComposeStream out;
out.linkStream(std::cout);
out << "To std::cout\n";
out.linkStream(std::clog);
out << "To: std::cout and std::clog\n";
std::ofstream file("Plop");
out.linkStream(file);
out << "To all three locations\n";
}
https://stackoverflow.com/questions/1760726
复制相似问题