0

I need precise Unicode-output to the console. If I imbue wcout to "en_US.UTF8" the characters are mapped to UTF-8 but they arent correctly displayed by the console. So I wrote a little helper function:

void writeOutput( wchar_t const *str, bool err )
{
    static mutex      mtx;
    lock_guard<mutex> lock( mtx );
    wstringstream wss;
    wss << str << L"\n";
    wstring strFmt = move( wss.str() );
    DWORD   dwWritten;
    WriteConsoleW( GetStdHandle( !err ?  STD_OUTPUT_HANDLE : STD_ERROR_HANDLE ), strFmt.c_str(), wcslen( strFmt.c_str() ), &dwWritten, nullptr );
}

This function correctly displays the Unicode-characters. But if I do I/O-redirection with "program > outfile" nothing is written in the file. So how do I detect that's there a redirection?

Bonita Montero
  • 2,817
  • 9
  • 22
  • Instead of imbuing UTF-8 locale you should [set UTF-8 in the manifest](https://learn.microsoft.com/en-us/windows/uwp/design/globalizing/use-utf8-code-page) and use regular i/o. – Yakov Galka Feb 09 '20 at 14:54
  • 1
    On Windows, redirection can usually be detected using `GetFileType()` or `GetConsoleMode()`. There are several questions on StackOverflow that discuss this (in other languages), such as [this one](https://stackoverflow.com/questions/9021916/). – Remy Lebeau Feb 09 '20 at 17:06
  • Hi Bonita Montero, you can [accept the answer](https://stackoverflow.com/help/someone-answers) if it solves your issue. – Rita Han Feb 11 '20 at 04:49

1 Answers1

0

So how do I detect that's there a redirection?

As @Remy Lebeau alreay pointed out, GetFileType function will return FILE_TYPE_DISK (The specified file is a disk file.) if console output has been redirected to a file.

The following is how to do in C++:

DWORD nType = GetFileType(GetStdHandle(err ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE));
if (FILE_TYPE_DISK == nType)
{
    printf("Output to a disk file.");
}
Rita Han
  • 9,574
  • 1
  • 11
  • 24