2

I would like to insert code into a C++ application running on Windows that can determine whether stdout (or cout) is pointing to the console, and if it is, convert characters to terminal encoding before writing them out. If not (for instance, if writing to a file or pipe), the characters should be left alone. The conversion part is not a problem, but I'm wondering whether it's even possible for an application to know whether its stdout is going to the console or elsewhere.

I am not sure whether the Windows API function GetStdHandle would be of any help, or whether it simply is a means of pointing to the stdout without being able to determine any information about it. Likewise, I'm not sure whether there's any information that we can obtain from cout that would indicate whether it's pointing to a console or something else. So far, I haven't been able to find anything along those lines.

Frxstrem
  • 38,761
  • 9
  • 79
  • 119
Alan
  • 1,889
  • 2
  • 18
  • 30
  • see also: https://stackoverflow.com/questions/3648711/detect-nul-file-descriptor-isatty-is-bogus – ecatmur Oct 21 '20 at 09:22

2 Answers2

4

Call GetConsoleMode (http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx) on the handle you want to know about. If it's redirected to something other than another console handle (e.g. to a file) then GetConsoleMode will fail. For example:

DWORD temp;
const BOOL success = GetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), &temp);
const bool redirected = success == FALSE;
Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
  • `WriteConsole` fails also, since it "paints" on the console. http://msdn.microsoft.com/en-us/library/windows/desktop/ms687401%28v=vs.85%29.aspx – Joe DF Apr 09 '14 at 19:44
  • Comparing to true/false is a code smell for me - I'd rather do `redirected = !success`. – Mark Ransom Jul 09 '14 at 23:01
  • I doubt I'd view "== FALSE" as a code smell--what deeper problem could that be an indication of that "!success" wouldn't be? I've encountered some people who simply don't like '!' in comparisons. So, at best case this is simply a religious thing and it wouldn't have mattered what I put there someone would have not liked it. – Peter Ritchie Jul 10 '14 at 14:26
  • does not work if it's console and output is redirected with > – TarmoPikaro Apr 03 '20 at 21:42
2

The GetFileType function allows you to distinguish between character-mode devices (such as the console) and files and pipes.

Harry Johnston
  • 35,639
  • 6
  • 68
  • 158