231-Cfg-OutputStreams.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. #define CATCH_CONFIG_NOSTDOUT
  8. #define CATCH_CONFIG_MAIN
  9. #include <catch2/catch.hpp>
  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. }