fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <fstream>
  5.  
  6. class raw_buffer : public std::streambuf
  7. {
  8. public:
  9. raw_buffer(std::ostream& os, int buf_size = 256);
  10. int_type overflow(int_type c) override;
  11. std::streamsize showmanyc() override;
  12. std::streamsize xsputn(const char_type*, std::streamsize) override;
  13. int sync() override;
  14. bool flush();
  15. std::string& str();
  16. virtual ~raw_buffer();
  17. private:
  18. std::ostream& os_;
  19. std::vector<char> buffer;
  20. std::string aux;
  21. };
  22.  
  23. raw_buffer::raw_buffer(std::ostream& os, int buf_size)
  24. : os_(os)
  25. , buffer(buf_size)
  26. {
  27. this->setp(buffer.data(), buffer.data() + buffer.size() - 1);
  28. }
  29.  
  30. std::streamsize raw_buffer::showmanyc()
  31. {
  32. return epptr() - pptr();
  33. }
  34.  
  35. bool raw_buffer::flush()
  36. {
  37. std::ptrdiff_t n = pptr() - pbase();
  38. return bool(os_.write(buffer.data(), n));
  39. }
  40.  
  41. int raw_buffer::sync()
  42. {
  43. return flush() ? 0 : -1;
  44. }
  45.  
  46. std::string& raw_buffer::str()
  47. {
  48. return aux;
  49. }
  50.  
  51. raw_buffer::int_type raw_buffer::overflow(raw_buffer::int_type c)
  52. {
  53. if (os_ && !traits_type::eq_int_type(c, traits_type::eof()))
  54. {
  55. aux += *this->pptr() = traits_type::to_char_type(c);
  56. this->pbump(1);
  57.  
  58. if (flush())
  59. {
  60. this->pbump(-(this->pptr() - this->pbase()));
  61. this->setp(this->buffer.data(),
  62. this->buffer.data() + this->buffer.size());
  63. return c;
  64. }
  65. }
  66. return traits_type::eof();
  67. }
  68.  
  69. std::streamsize raw_buffer::xsputn(const raw_buffer::char_type* str, std::streamsize count)
  70. {
  71. for (int i = 0; i < count; ++i)
  72. {
  73. if (traits_type::eq_int_type(this->sputc(str[i]), traits_type::eof()))
  74. return i;
  75. else
  76. aux += str[i];
  77. }
  78. return count;
  79. }
  80.  
  81. raw_buffer::~raw_buffer()
  82. {
  83. this->flush();
  84. }
  85.  
  86. class raw_ostream : private virtual raw_buffer
  87. , public std::ostream
  88. {
  89. public:
  90. raw_ostream(std::ostream& os) : raw_buffer(os)
  91. , std::ostream(this)
  92. { }
  93.  
  94. std::string& str()
  95. {
  96. return this->raw_buffer::str();
  97. }
  98.  
  99. std::streamsize count()
  100. {
  101. return this->str().size();
  102. }
  103. };
  104.  
  105. int main()
  106. {
  107. std::ofstream out("out.txt");
  108. raw_ostream rostr(out);
  109. rostr << "Hello, World " << 123 << std::boolalpha << true << false;
  110.  
  111. auto& buf = rostr.str();
  112. std::cout << "Content of the buffer: " << buf;
  113. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Content of the buffer: Hello, World 123truefalse