How do I suppress output while using a dynamic library?
You could try using setvbuf
to set stdout
to have a very large buffer and be fully buffered. Then, after every call to noisy_function
, clear out the buffer before flushing it to the stream. I think this invokes undefined behavior though.
Another way would be to redirect stdout to a temp file, like with this macro function.
#include <stdio.h>
#define QUIET_CALL(noisy) { \
FILE* tmp = stdout;\
stdout = tmpfile();\
(noisy);\
fclose(stdout);\
stdout = tmp;\
}
int main(){
QUIET_CALL(printf("blah blah"));
printf("bloo bloo\n");
return 0;
}
I have a suggestion, which lets you use the preprocessor for portability, or perhaps "portability".
If you try something like
#if defined __unix__
#define DEVNULL "/dev/null"
#elif defined _WIN32
#define DEVNULL "nul"
#endif
(ignoring other OSes, else case, error directive, etc.) and then reopen the file as before
FILE *myfile = freopen(DEVNULL, "w", stream);
then that may give you what you want.
I haven't tried this at home, though. The "nul" file exists; see /dev/null in Windows. And you can get predefined macros at "Pre-defined C/C++ Compiler Macros".