How to determine if stderr controls file output?

Is it possible to indicate whether stderr outputs to a file or terminal in a C / C ++ program? I need to display another error message depending on whether the program is called as:

./program

or how:

./program 2 → file

+4
source share
2 answers

Try using isatty() in the file descriptor:

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

The fileno() function checks the stream of arguments and returns its integer descriptor.

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

+11
source

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

 if(isatty(2)) // stderr is a terminal 
+10
source

All Articles