I want to suppress certain fprintf calls by redirecting the destination FILE to /dev/null. But can I be sure, that fopen("/dev/null", "w"); NEVER returns NULL. In other words, is it everytime possible to open this "file"?
If so, I could use this nice ternary operator:
FILE *whereToPrint = (strcmp(custom_topic, ERROR_TOPIC) == 0) ? fopen("/dev/null", "w") : stdout;
fprintf(whereToPrint, "Message sent!\n\n");
Yes, on a properly functioning system, /dev/null is world writable:
ls -l /dev/null
crw-rw-rw- 1 root root 1, 3 Jul 20 2017 /dev/null
So it'll always work. It's not the most efficient way to suppress output.. it would be better to simply not attempt to write if you don't want to.. but if it's not a lot of output, that won't matter.
Someone pointed out that it is possible for root to set the permissions of /dev/null so that it is not writable by other. Or they could delete the device altogether. This is true.. but it would result in a broken unix. /dev/null is supposed to have permissions as I showed above.. it is installed that way and should never be changed. Nevertheless, you should check the return value of fopen() or open() whenever opening any file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With