TITLE: designing stream for file and console output (Newsgroup comp.lang.c++, comp.lang.c++.moderated, 9 Jan 2000) ALBERT: albertland@hotmail.com > I am attempting to write a versatile log class that would allow > me to write text (and integers and floats and other custom types) > to files AND to a console, which would be derived from ostream. KUEHL: Dietmar Kuehl The approach to go is to derive a class from 'std::streambuf' (or, if you want to be really general, from 'std::basic_streambuf') which overrides the output functions, ie. basically 'overflow()' and 'xsputn()' for potentially better performance. An object of the derived class, call it 'teebuf', will get two stream buffers as constructor argument and sent received characters to these two stream buffers. Ie. basically the class would look like this: class teebuf: public std::streambuf { public: typedef std::char_traits traits_type; typedef traits_type::int_type int_type; teebuf(std::streambuf* sb1, std::streambuf* sb2): m_sb1(sb1), m_sb2(sb2) {} int_type overflow(int_type c) { if (m_sb1->sputc(c) == traits_type::eof() || m_sb1->sputc(c) == traits_type::eof()) return traits_type::eof(); return c; } private: std::streambuf* m_sb1; std::streambuf* m_sb2; }; The above code is not tested, not even compiled. However, it should be fairly close. For more information on stream buffers see eg. . I'm planning to submit a small collection of stream buffers to but I haven't done so. A tee buffer like the one above will certainly be part of the submission. Now, what does this help you? That's easy: You can construct an 'std::ostream' with a stream buffer. The stream buffer actually handles the writing and reading of characters while the stream is more or less only the interface for the formatting functions. Thus, you code might look something like this: #include #include "teebuf.h" int main() { std::ofstream logfile("/tmp/logfile.txt"); std::streambuf teebuf(std::cout.rdbuf(), logfile.rdbuf()); std::ostream log(&teebuf); // write log messages to 'log' } Of course, you might want to encapsulate the construction of the stream buffer in a class derived from 'std::ostream', say 'oteestream'. Doing such convenient construction is basically the only good reason to derive a class from 'std::ostream'. You might also want to search for past articles on similar topics at : I have written about this stuff a lot of times before. In addition, you will find some coverage of this stuff in "The C++ Standard Library", Nicolai Josuttis, Addison-Wesley, as this book describes the whole standard C++ library including the IOStreams portion of it. However, it is not a book addressing IOStreams specifically. _______________________________________________ cpptips mailing list http://cpptips.hyperformix.com