Mike McQuaid Mike McQuaid - 2 months ago 23
C Question

Detect if stdin is a terminal or pipe?

When I execute "

python
" from the terminal with no arguments it brings up the Python interactive shell.

When I execute "
cat | python
" from the terminal it doesn't launch the interactive mode. Somehow, without getting any input, it has detected that it is connected to a pipe.

How would I do a similar detection in C or C++ or Qt?

Answer

Use isatty:

#include <stdio.h>
#include <io.h>
...    
if (isatty(fileno(stdin)))
    printf( "stdin is a terminal\n" );
else
    printf( "stdin is a file or a pipe\n");

(On windows they're prefixed with underscores: _isatty, _fileno)