• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
9 #define CATCH_CONFIG_NOSTDOUT
10 #define CATCH_CONFIG_MAIN
11 #include <catch2/catch.hpp>
12 
13 class out_buff : public std::stringbuf {
14     std::FILE* m_stream;
15 public:
out_buff(std::FILE * stream)16     out_buff(std::FILE* stream) :m_stream(stream) {}
~out_buff()17     ~out_buff() { pubsync(); }
sync()18     int sync() {
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 namespace Catch {
cout()33     std::ostream& cout() {
34         static std::ostream ret(new out_buff(stdout));
35         return ret;
36     }
clog()37     std::ostream& clog() {
38         static std::ostream ret(new out_buff(stderr));
39         return ret;
40     }
cerr()41     std::ostream& cerr() {
42         return clog();
43     }
44 }
45 
46 
47 TEST_CASE("This binary uses putc to write out output", "[compilation-only]") {
48     SUCCEED("Nothing to test.");
49 }
50