Dave's Brain

Browse - Programming Tips - How can my program tell if it's output has been redirected?

Date: 2009sep4
Language: C/C++

Q.  How can my program tell if it's output has been redirected?

A.  This does the trick:

#include <io.h> const bool bInteractive = isatty(fileno(stdout));
Example use:
if (isatty(fileno(stdout))) { printf("We ARE interactive (no redirection)\n"); } else { printf("We are NOT interactive (being redirected)\n"); }
This works on Linux and Borland C++ 5.x (which is nice). 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.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.