Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028 #ifndef CConsoleRedirector_H
00029 #define CConsoleRedirector_H
00030
00031 #include <streambuf>
00032 #include <iostream>
00033
00034
00035 namespace mrpt
00036 {
00037 namespace utils
00038 {
00039
00040
00041
00042
00043 class CConsoleRedirector : public std::streambuf
00044 {
00045 protected:
00046 std::ofstream m_of;
00047 std::streambuf *sbOld;
00048 std::streambuf *sbOld_cerr;
00049 bool m_also_to_console;
00050 mrpt::synch::CCriticalSection m_cs;
00051
00052 public:
00053
00054
00055
00056
00057
00058
00059
00060
00061 CConsoleRedirector(
00062 const std::string &out_file,
00063 bool also_to_console=true,
00064 bool also_cerr = true,
00065 bool append_file = false,
00066 int bufferSize = 1000 ) : m_of(), sbOld(NULL),sbOld_cerr(NULL),m_also_to_console(also_to_console), m_cs()
00067 {
00068
00069 std::ios_base::openmode openMode = std::ios_base::binary | std::ios_base::out;
00070 if ( append_file ) openMode |= std::ios_base::app;
00071 m_of.open(out_file.c_str(), openMode );
00072 if (!m_of.is_open()) THROW_EXCEPTION_CUSTOM_MSG1("Error opening file: %s",out_file.c_str())
00073
00074 if (bufferSize)
00075 {
00076 char *ptr = new char[bufferSize];
00077 setp(ptr, ptr + bufferSize);
00078 }
00079 else
00080 setp(0, 0);
00081
00082
00083 sbOld = std::cout.rdbuf();
00084 std::cout.rdbuf( this );
00085
00086 if (also_cerr)
00087 {
00088 sbOld_cerr = std::cerr.rdbuf();
00089 std::cerr.rdbuf( this );
00090 }
00091 }
00092
00093 virtual ~CConsoleRedirector()
00094 {
00095 sync();
00096
00097 std::cout.rdbuf(sbOld);
00098 if (sbOld_cerr!=NULL) std::cerr.rdbuf( sbOld_cerr );
00099 if (pbase()) delete[] pbase();
00100 }
00101
00102 void flush()
00103 {
00104 sync();
00105 }
00106
00107 virtual void writeString(const std::string &str)
00108 {
00109 if (m_also_to_console) sbOld->sputn(str.c_str(),str.size());
00110 m_of << str;
00111 }
00112
00113 private:
00114 int overflow(int c)
00115 {
00116 sync();
00117
00118 m_cs.enter();
00119 if (c != EOF)
00120 {
00121 if (pbase() == epptr())
00122 {
00123 std::string temp;
00124 temp += char(c);
00125 writeString(temp);
00126 }
00127 else
00128 sputc(c);
00129 }
00130
00131 m_cs.leave();
00132 return 0;
00133 }
00134
00135 int sync()
00136 {
00137 m_cs.enter();
00138 if (pbase() != pptr())
00139 {
00140 int len = int(pptr() - pbase());
00141 std::string temp(pbase(), len);
00142 writeString(temp);
00143 setp(pbase(), epptr());
00144 }
00145 m_cs.leave();
00146 return 0;
00147 }
00148 };
00149
00150 }
00151 }
00152
00153 #endif