Advertisement
jpenguin

teebuff.h

Mar 11th, 2022
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. // https://forums.devx.com/showthread.php?175218-streambuf
  2. // Created by vijayan on 11/25/10.
  3. //
  4.  
  5. #ifndef TEEBUFF_H_
  6. #define TEEBUFF_H_
  7.  
  8. #include <iostream>
  9.  
  10. template<typename CHAR_TYPE,
  11. typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
  12.  
  13. struct basic_teebuf : public std::basic_streambuf<CHAR_TYPE, TRAITS_TYPE> {
  14. typedef std::basic_streambuf<CHAR_TYPE, TRAITS_TYPE> streambuf_type;
  15. typedef typename TRAITS_TYPE::int_type int_type;
  16.  
  17. basic_teebuf(streambuf_type *buff_a, streambuf_type *buff_b)
  18. : first(buff_a), second(buff_b) {}
  19.  
  20. protected:
  21. virtual int_type overflow(int_type c) {
  22. const int_type eof = TRAITS_TYPE::eof();
  23. if (TRAITS_TYPE::eq_int_type(c, eof))
  24. return TRAITS_TYPE::not_eof(c);
  25. else {
  26. const CHAR_TYPE ch = TRAITS_TYPE::to_char_type(c);
  27. if (TRAITS_TYPE::eq_int_type(first->sputc(ch), eof) ||
  28. TRAITS_TYPE::eq_int_type(second->sputc(ch), eof))
  29. return eof;
  30. else
  31. return c;
  32. }
  33. }
  34.  
  35. virtual int sync() {
  36. return !first->pubsync() && !second->pubsync() ? 0 : -1;
  37. }
  38.  
  39. private:
  40. streambuf_type *first;
  41. streambuf_type *second;
  42. };
  43.  
  44. template<typename CHAR_TYPE,
  45. typename TRAITS_TYPE = std::char_traits<CHAR_TYPE> >
  46. struct basic_teestream : public std::basic_ostream<CHAR_TYPE, TRAITS_TYPE> {
  47. typedef std::basic_ostream<CHAR_TYPE, TRAITS_TYPE> stream_type;
  48. typedef basic_teebuf<CHAR_TYPE, TRAITS_TYPE> streambuff_type;
  49.  
  50. basic_teestream(stream_type &first, stream_type &second)
  51. : stream_type(&stmbuf), stmbuf(first.rdbuf(), second.rdbuf()) {}
  52.  
  53. ~basic_teestream() { stmbuf.pubsync(); }
  54.  
  55. private:
  56. streambuff_type stmbuf;
  57. };
  58.  
  59. typedef basic_teebuf<char> teebuf;
  60. typedef basic_teestream<char> teestream;
  61.  
  62. #endif // TEEBUFF_H_
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement