fork(3) download
  1. #include <streambuf>
  2. #include <ostream>
  3. #include <iostream>
  4.  
  5. //#define DEBUG
  6.  
  7. class MyData
  8. {
  9. //example data class, not used
  10. };
  11.  
  12. class MyBuffer : public std::basic_streambuf<char, std::char_traits<char> >
  13. {
  14.  
  15. public:
  16.  
  17. inline MyBuffer(MyData data) :
  18. data(data)
  19. {
  20. setp(buf, buf + BUF_SIZE);
  21. }
  22.  
  23. protected:
  24.  
  25. // This is called when buffer becomes full. If
  26. // buffer is not used, then this is called every
  27. // time when characters are put to stream.
  28. inline virtual int overflow(int c = Traits::eof())
  29. {
  30. #ifdef DEBUG
  31. std::cout << "(over)";
  32. #endif
  33. // Handle output
  34. putChars(pbase(), pptr());
  35. if (c != Traits::eof()) {
  36. char c2 = c;
  37. // Handle the one character that didn't fit to buffer
  38. putChars(&c2, &c2 + 1);
  39. }
  40. // This tells that buffer is empty again
  41. setp(buf, buf + BUF_SIZE);
  42.  
  43. return c;
  44. }
  45.  
  46. // This function is called when stream is flushed,
  47. // for example when std::endl is put to stream.
  48. inline virtual int sync(void)
  49. {
  50. // Handle output
  51. putChars(pbase(), pptr());
  52. // This tells that buffer is empty again
  53. setp(buf, buf + BUF_SIZE);
  54. return 0;
  55. }
  56.  
  57. private:
  58.  
  59. // For EOF detection
  60. typedef std::char_traits<char> Traits;
  61.  
  62. // Work in buffer mode. It is also possible to work without buffer.
  63. static const size_t BUF_SIZE = 64;
  64. char buf[BUF_SIZE];
  65.  
  66. // This is the example userdata
  67. MyData data;
  68.  
  69. // In this function, the characters are parsed.
  70. inline void putChars(const char* begin, const char* end){
  71. #ifdef DEBUG
  72. std::cout << "(putChars(" << static_cast<const void*>(begin) <<
  73. "," << static_cast<const void*>(end) << "))";
  74. #endif
  75. //just print to stdout for now
  76. for (const char* c = begin; c < end; c++){
  77. std::cout << *c;
  78. }
  79. }
  80.  
  81. };
  82.  
  83. class MyOStream : public std::basic_ostream< char, std::char_traits< char > >
  84. {
  85.  
  86. public:
  87.  
  88. inline MyOStream(MyData data) :
  89. std::basic_ostream< char, std::char_traits< char > >(&buf),
  90. buf(data)
  91. {
  92. }
  93.  
  94. private:
  95.  
  96. MyBuffer buf;
  97.  
  98. };
  99.  
  100. int main(void)
  101. {
  102. MyData data;
  103. MyOStream o(data);
  104.  
  105. for (int i = 0; i < 8; i++)
  106. o << "hello world! ";
  107.  
  108. o << std::endl;
  109.  
  110. return 0;
  111. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
hello world! hello world! hello world! hello world! hello world! hello world! hello world! hello world!