views:

173

answers:

2

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.

+7  A: 

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

Oh, and the "o" flag to fopen() is non-portable. The portable forms include flag characters r, w, a, b, + in various combinations.

Jonathan Leffler
what does the "o" flag do? it's not in my manpages
Matt Joiner
"O"K, I knew I should have looked that up. I was working from memory.
BCS
@Anacrolix: I've no idea what 'o' does; it isn't portable and doesn't apply to the systems I have available...I think it was intended to be a variant on 'w'.
Jonathan Leffler
why the `:` - on Windows, the null device is called `NUL` (see eg http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx#naming_conventions for a complete list of reserved file names)
Christoph
@Christoph: because I was under the illusion that the colon was either necessary or desirable to indicate that it was the device that you wanted. If it fails with the colon, it is a fixable fault in my answer; if the colon is merely unnecessary, then put it down to a bad habit picked up sometime in the previous millennium. I am not completely alone in my understanding - see http://en.wikipedia.org/wiki/DOS#Reserved_device_names.
Jonathan Leffler
+4  A: 

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 :)

Pod
a) for that much work I could switch to a real logging system. b) that's worth looking into +1
BCS
b)a quick look around seems to indicate that `fprintf(NULL,"");` will fail.
BCS
All you would have to do is add one function and search + replace for all instances for fprintf(stderr).
Pod
I thought it might. C std lib tends not to check it's parameters.
Pod
Passing a null file pointer to fprintf() leads to undefined behaviour, and usually to a crash and core dump on Unix-like systems.
Jonathan Leffler