Suppressing stdout output

P

Peter Ammon

Let's say I want to call a function but suppress what it writes to
stdout. One way that works on my machine is this:

#include <stdio.h>
int main(void) {
freopen("/dev/null", "w", stdout);
puts("Hello");
return 0;
}

but how do I restore the original stdout in a portable way? And is
there a portable way to avoid using /dev/null? I could write to a
temporary file, but that uselessly fills up the hard drive.

Thanks for your thoughts.
-Peter
 
E

Eric Sosman

Peter said:
Let's say I want to call a function but suppress what it writes to
stdout. One way that works on my machine is this:

#include <stdio.h>
int main(void) {
freopen("/dev/null", "w", stdout);
puts("Hello");
return 0;
}

but how do I restore the original stdout in a portable way? And is
there a portable way to avoid using /dev/null? I could write to a
temporary file, but that uselessly fills up the hard drive.

This is Question 12.34 in the comp.lang.c Frequently
Asked Questions (FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html

.... and you're not going to like the answer.
 
D

Dan Pop

In said:
Let's say I want to call a function but suppress what it writes to
stdout. One way that works on my machine is this:

#include <stdio.h>
int main(void) {
freopen("/dev/null", "w", stdout);
puts("Hello");
return 0;
}

but how do I restore the original stdout in a portable way?

You cannot.
And is there a portable way to avoid using /dev/null?
Nope.

I could write to a
temporary file, but that uselessly fills up the hard drive.

The idea is to use the 'f' flavour of the output functions (e.g. fprintf
and fputs) and to manipulate the FILE pointer variable they use.

#define NULLDEVICE "/dev/null"

FILE *nulldev = fopen(NULLDEVICE, "w");
FILE *output;

Do all your "suppressable" output via the "output" FILE pointer and
set it to either nulldev or stdout, according to your needs. Most
platforms support the concept of null device, but, of course, you have
to define the NULLDEVICE macro as appropriate.

If you want to avoid this portability issue, you can set "output" to
either stdout or NULL. In this case, however, each output call must
be prefixed by "if (output != NULL)". This can be trivially handled with
wrapper functions (or even macros, for non-variadic functions):

#define FPUTS(string, stream) (stream != NULL ? fputs(string, stream) : 0)

Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top