1 #ifndef PRINT_H 2 #define PRINT_H 3 4 #include5 class ReplaceStdout 6 { 7 public: 8 ReplaceStdout(); 9 ~ReplaceStdout();10 bool isOK() { return _ok; }11 private:12 bool _ok;13 };14 void print(const char* format, ...);15 #endif
1 #include "print.h" 2 #include3 #include 4 5 const static char* name = "/dev/null"; 6 static FILE* std_file = fopen(name, "w"); 7 8 bool replace() 9 {10 if (std_file) {11 fflush(stdout);12 std::swap(stdout->_fileno, std_file->_fileno);13 return true;14 }15 return false;16 }17 18 ReplaceStdout::ReplaceStdout():19 _ok(replace())20 {21 }22 23 ReplaceStdout::~ReplaceStdout()24 {25 replace();26 }27 28 void print(const char* format, ...)29 {30 va_list args;31 va_start(args, format);32 vfprintf(1 == stdout->_fileno ? stdout : std_file,33 format, args);34 va_end(args);35 }
1 #include "print.h" 2 3 int main(int argc, char* argv[]) 4 { 5 ReplaceStdout replace; 6 printf("printf hello\n"); 7 print("print hello\n"); 8 //{ ReplaceStdout replace; } 9 ReplaceStdout recover;10 printf("printf world\n");11 print("print world\n");12 return 0;13 }