| 1 | // 231-Cfg-OutputStreams.cpp |
| 2 | // Show how to replace the streams with a simple custom made streambuf. |
| 3 | |
| 4 | // Note that this reimplementation _does not_ follow `std::cerr` |
| 5 | // semantic, because it buffers the output. For most uses however, |
| 6 | // there is no important difference between having `std::cerr` buffered |
| 7 | // or unbuffered. |
| 8 | #include <catch2/catch_test_macros.hpp> |
| 9 | |
| 10 | #include <sstream> |
| 11 | #include <cstdio> |
| 12 | |
| 13 | class out_buff : public std::stringbuf { |
| 14 | std::FILE* m_stream; |
| 15 | public: |
| 16 | out_buff(std::FILE* stream):m_stream(stream) {} |
| 17 | ~out_buff(); |
| 18 | int sync() override { |
| 19 | int ret = 0; |
| 20 | for (unsigned char c : str()) { |
| 21 | if (putc(c, m_stream) == EOF) { |
| 22 | ret = -1; |
| 23 | break; |
| 24 | } |
| 25 | } |
| 26 | // Reset the buffer to avoid printing it multiple times |
| 27 | str(""); |
| 28 | return ret; |
| 29 | } |
| 30 | }; |
| 31 | |
| 32 | out_buff::~out_buff() { pubsync(); } |
| 33 | |
| 34 | #if defined(__clang__) |
| 35 | #pragma clang diagnostic ignored "-Wexit-time-destructors" // static variables in cout/cerr/clog |
| 36 | #endif |
| 37 | |
| 38 | namespace Catch { |
| 39 | std::ostream& cout() { |
| 40 | static std::ostream ret(new out_buff(stdout)); |
| 41 | return ret; |
| 42 | } |
| 43 | std::ostream& clog() { |
| 44 | static std::ostream ret(new out_buff(stderr)); |
| 45 | return ret; |
| 46 | } |
| 47 | std::ostream& cerr() { |
| 48 | return clog(); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | |
| 53 | TEST_CASE("This binary uses putc to write out output", "[compilation-only]") { |
| 54 | SUCCEED("Nothing to test."); |
| 55 | } |