I want my program to have different behaviors between when stderr is connected to a console and when it is redirected to a file/pipe. In Unix systems I can just test isatty(STDERR_FILENO)
, but how do I do that in Windows? MSVCRT also has a function named _isatty
, it doesn't function properly (for example, Detect NUL file descriptor (isatty is bogus)). Is there any Windows or NT API I can call to test it?
Asked
Active
Viewed 496 times
3

IInspectable
- 46,945
- 8
- 85
- 181

Siyuan Ren
- 7,573
- 6
- 47
- 61
-
1C and C++ are different languages. Which do you use? – too honest for this site Feb 09 '17 at 15:22
-
1@Olaf: It doesn't matter. The Windows API can be consumed from both C and C++. It is standard practice to ask for a solution in C or C++ (which doesn't make a difference). – IInspectable Feb 09 '17 at 15:24
-
@IInspectable: If that is a matter of the WinAPI, it uses C binding, thus it is a C question. – too honest for this site Feb 09 '17 at 15:26
-
The [accepted answer from the question you linked to](https://stackoverflow.com/questions/3648711/detect-nul-file-descriptor-isatty-is-bogus#3650507) has the solution, except you need to use `STD_ERROR_HANDLE` instead of `STD_OUTPUT_HANDLE`). – Ian Abbott Feb 09 '17 at 15:27
2 Answers
4
- Call
GetStdHandle
to get the stderr handle. - Pass that handle to
GetFileType
to find out what type of file it is. - If that returns
FILE_TYPE_CHAR
then stderr could be a console, but callGetConsoleMode
to check. - If
GetConsoleMode
fails then stderr has been redirected to another character device, such as a printer.

David Heffernan
- 601,492
- 42
- 1,072
- 1,490
-
This is not enough, as explained in the [proposed duplicate](http://stackoverflow.com/q/40709193/1889329). – IInspectable Feb 09 '17 at 15:25
-
Will `GetConsoleMode` ever succeeds if the handle is not a character device? If not, then the `GetFileType` is redundant. – Siyuan Ren Feb 10 '17 at 01:56