C++ streams
Hello!
I wonder if it''s possible to create a stream in C++ which would output the data both on the stdout (screen) and to a file? Is there any way to do that or do I have to simply use two different streams?
Thanks in advance!
-------------
... you got me on my knees, Layla
The good news is that it''s possible.
The bad news is that it''s annoying.
The simplest method I can think of to do this is to create a custom streambuf class and override the sync() and overflow() members. Most likely, you''d need to grab the rdbufs from the streams that you want to write to, and call the sputc() member functions on each rdbuf for overflow(). Then for the sync() member function, call the pubsync() member functions on each rdbuf.
Without compiling it, I''d imagine a streambuf for this would look like:
To use it:
The bad news is that it''s annoying.
The simplest method I can think of to do this is to create a custom streambuf class and override the sync() and overflow() members. Most likely, you''d need to grab the rdbufs from the streams that you want to write to, and call the sputc() member functions on each rdbuf for overflow(). Then for the sync() member function, call the pubsync() member functions on each rdbuf.
Without compiling it, I''d imagine a streambuf for this would look like:
class twinbuf : public std::streambuf { protected: std::streambuf * buf1_; std::streambuf * buf2_; public: twinbuf(std::streambuf * buf1, std::streambuf * buf2) : buf1_(buf1), buf2_(buf2) {} virtual ~twinbuf() { sync(); } protected: virtual int_type overflow (int_type c) { if (c != EOF) { buf1_->sputc(traits_type::to_char_type(c)); buf2_->sputc(traits_type::to_char_type(c)); } return c; } virtual int sync () { if (buf1_->pubsync() == -1) return -1; if (buf2_->pubsync() == -1) return -1; return 0; }};
To use it:
int main(int, char **) { std::ofstream ofs("filename.txt"); twinbuf tb(std::cout.rdbuf(), ofs.rdbuf()); std::ostream os(&tb); os << "Hello World" << std::endl; // should write to both file and stdout return 0;}
struct twin_ostream { twin_ostream(std::ostream& os1, std::ostream& os2) : m_os1(os1), m_os2(os2) {} std::ostream& m_os1; std::ostream& m_os2;};template<typename T>twin_ostream& operator<<(twin_ostream& os, const T& obj) { os.m_os1 << obj; os.m_os2 << obj; return os;}
not a fully functional ostream but you get the idea.
Thanks for your help!
Frankly speaking, I thought that the solution will be a bit simpler. Anyway, I can now handle that with your code.
Bye!
-----------
... you got me on my knees, Layla
Frankly speaking, I thought that the solution will be a bit simpler. Anyway, I can now handle that with your code.
Bye!
-----------
... you got me on my knees, Layla
http://www.flipcode.com/cgi-bin/msg.cgi?showThread=COTD-MessageBoxostream&forum=cotd&id=-1
I think the tee stream here might also work.
I think the tee stream here might also work.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement