Scranton
Scranton

Reputation: 339

Mute printf without macros

Is there a way I can mute all my printf statements conditionally, however, without using any macros? I want to accomplish the muting without touching the already existing code, but adding a line to my module which would simply disable all printf's already existing in the source code.

Thanks!

Upvotes: 0

Views: 607

Answers (4)

Wendel Melo
Wendel Melo

Reputation: 1

You can try this. It worked in my situation (Linux/GCC) (It should works in both Unix and Windows, but I have not test in Windows).

//saving current stdout descriptor
FILE oldstdout = *stdout;
//open a output stream to null
FILE *mystdout = fopen("/dev/null", "w"); //to unix
if( !mystdout )        
    mystdout = fopen("NUL", "w"); // to Windows

*stdout = *mystdout; //replacing stdout by our stream to null

/*******  PUT YOUR CODE HERE TO BE "MUTED" *******/

//enabling back stdout 
*stdout = oldstdout;
fclose(mystdout);   //closing my null stream

The advantage of this solution is stdout is never closed. So, the original stdout can be restored at any time as it is necessary. We also do not have any risk of stdout file descriptor be assigned to another output stream.

Upvotes: 0

Adam Rosenfield
Adam Rosenfield

Reputation: 400454

If you want to nullify all output to stdout via printf, puts, putchar, etc., you can use freopen(3) to redirect it to a bit bucket, e.g.:

// On Unix and Unix-like systems:
freopen("/dev/null", "w", stdout);
// On Windows:
freopen("NUL", "w", stdout);

Upvotes: 3

Zan Lynx
Zan Lynx

Reputation: 54345

On Linux, BSD or other Unix you could create a shared library which provides its own printf and wraps the C library printf.

Then you would load it ahead of the C library using LD_PRELOAD=mylib.so ./myprogram

Upvotes: 2

Eric Postpischil
Eric Postpischil

Reputation: 223389

Replace the library printf with your own implementation by adding this to your source code:

int printf(const char * restrict format,...) { return 0; }

Upvotes: 0

Related Questions