Programming Tips - C/C++: How can my program tell if it's output has been redirected

Date: 2009sep4 Update: 2026oct1 OS: Linux Language: C/C++ Q. C/C++: How can my program tell if it's output has been redirected A. This does the trick:
#include <unistd.h> const bool bInteractive = isatty(fileno(stdout)); // Not you can use bInteractive
This works on Linux and Borland C++ 5.x (but its obsolete). The Linux "less" command uses this. If you do:
less myfile.txt
Then less pages the file. And you can scroll backwards and forwards. But if you do:
less myfile.txt > anotherfile.txt
Then less does not offer any paging. Full Example Use:
#include <unistd.h> #include <stdio.h> int main() { if (isatty(fileno(stdout))) { fprintf(stderr, "We ARE interactive (no redirection)\n"); } else { fprintf(stderr, "We are NOT interactive (being redirected)\n"); } }
Run as:
./tst >/dev/null
Output:
We are NOT interactive (being redirected)