Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FILE* that goes nowhere

Is there a way to get a C stream object (a FILE* object) that points at nothing?

I know fopen("/dev/null","w"); would work but I'm wondering if there is a better way.

Preferably that bit buckets the data at a higher level than the posix layer and that is also more portable.

like image 658
BCS Avatar asked Dec 13 '09 01:12

BCS


2 Answers

No: /dev/null on Unix and NUL: on Windows (in the absence of Cygwin or equivalent) is the best way to do it.

(The original version of the question mentioned fopen("/dev/null","o"); but has since been fixed.)
Oh, and the "o" flag to fopen() is non-portable. The portable forms include flag characters r, w, a, b, + in various combinations.

like image 180
Jonathan Leffler Avatar answered Sep 19 '22 13:09

Jonathan Leffler


I have some logging in place that goes to stderr and I want to be able to turn it off with a flag. I'd really rather not have to do more to it than change the variable that gets passed to fprintf

a) Wrapper function

logging = TRUE;
void debugprint(...)
{
    if (logging)   
    {
        fprintf(stderr, ...);
    }
}

b) I think fprintf will return if you give it a null pointer. Can't remember -- give it a try. Then all you have to do is change the pointer :)

like image 34
Pod Avatar answered Sep 17 '22 13:09

Pod