I am trying to learn more about the operation of the C ++ I / O Thread Library by expanding std::streambuf
. As a training experiment, my goal is simply to create a custom thread that directs all output to std::cerr
. This seems simple enough:
#include <iostream> using namespace std; class my_ostreambuf : public std::streambuf { public: protected: std::streamsize xsputn(const char * s, std::streamsize n) { std::cerr << "Redirecting to cerr: " << s << std::endl; return n; } }; int main() { my_ostreambuf buf; std::ostream os(&buf); os << "TEST"; }
This seems to work as it prints Redirecting to cerr: TEST
. The problem is that it does not work when a single character (as opposed to a string) is inserted into the stream through std::ostream::sputc
. For instance:
int main() { my_ostreambuf buf; std::ostream os(&buf); os << "ABC"; // works std::string s("TEST"); std::copy(s.begin(), s.end(), std::ostreambuf_iterator<char>(os)); // DOESN'T WORK }
The problem is, I think xsputn
does not handle single character insertion. (I think sputc
does not call xsputn
internally?) But, by looking at the list of virtual protected functions in std::streambuf
, I don't see any function that I have to override that handles the insertion of a single character.
So how can I do this?
source share