Mike McQuaid Mike McQuaid - 1 year ago 76
C Question

Detect if stdin is a terminal or pipe?

When I execute "

" 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 Source

Use isatty:

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

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