Dave's Brain

Browse - programming tips - how can my program tell if its output is 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>

	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.
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2010, 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.