231-Cfg-OutputStreams.cpp 1.4 KB

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