In <ca**********@news.apple.com> Peter Ammon <pe*********@rocketmail.com> writes:
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
--
Dan Pop
DESY Zeuthen, RZ group
Email:
Da*****@ifh.de