How do I know if console handle is redirected?


In a console application, how does it know if the console standard handle has been redirected (to a pipe or file) or not?


You can use GetStdHandle to get the standard handle, then use GetFileType to determine the type of the handle.


If the file type is not FILE_TYPE_CHAR, you know the console handle is redirected.

Comments (4)

  1. Note that you can be redirected to a character device, in which case you will still get FILE_TYPE_CHAR back.

  2. From MSDN, it seems the only other non-console character device is printer. Not sure how many people still use that nowadays.

    Do you have better ways to distinguish this Raymond?

  3. Marc Brooks says:

    How about detecting the underlying device name? Specifically, is it NUL:

  4. Andrej says:

    There is this undocumented Kernel32 function BOOL WINAPI VerifyConsoleIoHandle(HANDLE) that one can use instead or additionally to GetFileType().

    There are at least two types of non-console character devices; that’s lpt and com.