Re: output to 2 streams

Discussion in 'C++' started by Dietmar Kuehl, Aug 26, 2004.

  1. Fraser Ross wrote:
    > My program outputs to cout and I want it to output to a LOG file as

    well.
    > Is there a simple way to do that?


    It depends on your measure of simple. The trick is to implement a
    stream buffer writing to two other stream buffers and installing
    this stream buffer into 'std::cout'. To avoid problems during
    clean-up, the original stream buffer shall be restored into
    'std::cout' at the end of the program.

    Here is some untested code for this:

    struct teebuf: std::streambuf {
    teebuf(std::streambuf* sb1, std::streambuf* sb2):
    m_sb1(sb1), m_sb2(sb2)
    {
    }
    private:
    int_type overflow(int_type c) {
    if (!traits_type::eq_int_type(c, traits_type::eof()))
    {
    m_sb1->sputc(c);
    m_sb2->sputc(c);
    }
    return traits_type::not_eof(c);
    }
    int sync() {
    m_sb1->pubsync();
    m_sb2->pubsync();
    return 0;
    }
    std::streambuf* m_sb1;
    std::streambuf* m_sb2;
    };

    int main()
    {
    std::streambuf* cout_sbuf = std::cout.rdbuf();
    std::eek:fstream log("log");
    teebuf tbuf(std::cout.rdbuf(), log.rdbuf());
    std::cout.rdbuf(&tbuf);

    std::cout << "this goes both to cout and to the log file\n";

    std::cout.rdbuf(cout_sbuf);
    }

    Of course, a real tee buffer would provide more error handling,
    e.g. propagating errors from underlying stream buffers.
    --
    <mailto:> <http://www.dietmar-kuehl.de/>
    <http://www.contendix.com> - Software Development & Consulting
     
    Dietmar Kuehl, Aug 26, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Pawel Banys
    Replies:
    1
    Views:
    494
    Joe Smith
    Jul 8, 2004
  2. Ike
    Replies:
    1
    Views:
    1,956
  3. Marcus Leon

    Shell output vs Process streams

    Marcus Leon, Jul 27, 2005, in forum: Java
    Replies:
    1
    Views:
    2,435
    Gordon Beaton
    Jul 27, 2005
  4. Michael Grove
    Replies:
    5
    Views:
    2,151
    Michael Grove
    Aug 23, 2005
  5. Fraser Ross

    output to 2 streams

    Fraser Ross, Aug 26, 2004, in forum: C++
    Replies:
    19
    Views:
    546
    Fraser Ross
    Sep 15, 2004
Loading...

Share This Page