views:

208

answers:

2

Is there a way I can tell whether stderr is outputting to a file or the terminal within a C/C++ program? I need to output different error message depending on whether the program is invoked as:

./program

or like:

./program 2>> file

+9  A: 

Yes, you can use isatty(3) to tell if a file descriptor refers to the terminal or to something else (file, pipe, etc.). File descriptor 0 is stdin, 1 is stdout, and 2 is stderr.

if(isatty(2))
    // stderr is a terminal
Adam Rosenfield
How reliable is that on windows?
JesperE
It doesn't exist on Windows (unless you're compiling under Cygwin, in which case it's 100% reliable).
Adam Rosenfield
Was that sarcasm? Is any part of Cygwin 100% reliable?
bk1e
It was more of me joshing JesperE for his choice of the word 'reliable'. I assume he was asking whether it existed on Windows, not whether or not it worked all the time. And it's true, no software can ever be said to be 100% reliable, but 99.999% is good enough for most people.
Adam Rosenfield
+10  A: 

Try using isatty() on the file descriptor:

The isatty() function determines if the file descriptor fd refers to a valid terminal type device.

The function fileno() examines the argument stream and returns its integer descriptor.

Note that stderr is always on file descriptor 2, so you don't really need fileno() in this exact case.

winden