How to reload printf or cout

I use cout instructions in my program for debugging purposes. I would like to create a function that works like this, or works like printf, but is sensitive to a global variable. If this global variable is true, then it will be displayed. If it is incorrect, it does not print anything. Is there such a function? If not, how can this be done?

+4
source share
3 answers

Something like that:

int myPrintf(const char* format, ...) { if (globalCheck == 0) return 0 va_list vl; va_start(vl, format); auto ret = vprintf(format, vl); va_end(vl); return ret; } 

va_start and va_end take the arguments in ... and encapsulate them in va_list . with this va_list you can then vprintf , which is a printf variant designed specifically for this need.

A side note is usually a bad practice using global variables. The best thing is to encapsulate it in a class like this -

 class ConditionalPrinter { public: ConditionalPrinter() : m_enable(true) {} void setOut(bool enable) { m_enable = enable; } int myPrintf(const char* format, ...); private: bool m_enable; } 

and then check m_enable instead of a global variable. Using this is as follows:

 ConditionalPrinter p; p.myPrintf("hello %d", 1); // printed p.setOut(false); p.myPrintf("hello2 %d", 1); // not printed 

....

+5
source

Do not write yourself. Proper execution is much more complicated than you think. Even harder when you need threads and efficiency. Use one of the existing logging libraries, for example:

+3
source

As someone else said, there are some good frameworks. However, if you want to collapse your own, the first thing to note is that cout is not a function, it is a stream. Function operator<< . What you can do is something like the following:

 /* trace.h */ extern ostream debug; void trace_init(); void trace_done(); /* trace.cpp */ #include "trace.h" ostream debug(cout.rdbuf()); static ofstream null; void trace_init() { null.open("/dev/null"); if(output_is_disabled) { // put whatever your condition is here debug.rdbuf(null.rdbuf()); } } void trace_done() { null.close(); } 

You may need to adjust a bit if you are on a platform without /dev/null . It allows you to write

 debug << "here some output << endl; 

and if you turned on the output, it will write cout. If not, it will write to /dev/null where you will not see anything.

In this case, you can just set cout rdbuf somewhere where you will not see this output, but I would consider this to be a really bad idea. Creating new threads gives you great flexibility in managing your output.

+2
source

All Articles