Reputation: 13948
The target application can be used in "pipe" mode, which means it accepts input from stdin, and can output into stdout.
However, there is always a risk of a user making a mistake, directing output to stdout, without actually directing stdout towards "something" (a file, or a consumer program). As a consequence, the console screen gets garbaged displaying binary data (since by default, stdout outputs to the screen).
Bottom line : I want to avoid binary output to be displayed into the console, automatically. It must be done in portable C, and not depend on external script.
A few potential ways of doing it :
1) Is it possible to detect that stdout is going to console, in order to redirect it somewhere else instead ? (including /dev/nul). Note that the code must be portable, and work for Windows and Linux (and BSD, OpenSolaris, etc.)
2) Alternative : is it possible to redirect stdout to "somewhere else" (such as /dev/nul) by default without actually harming a correct usage of the program, redirecting stdout to a valid consumer process ?
Upvotes: 0
Views: 257
Reputation: 409166
On a POSIX (e.g. Linux and OSX) system you can use the isatty
function to check if stdout
goes to a console or to something else:
if (isatty(STDOUT_FILENO))
printf("Going to a console\n");
else
printf("Standard output is redirected or piped\n");
Unfortunately there is no portable way to do this that works on both POSIX systems and Windows.
Upvotes: 4