首页 > 解决方案 > 如何使用 Windows 检测“stdout”/“sterr”的 I/O 重定向

问题描述

我需要精确的 Unicode 输出到控制台。如果我将 wcout 灌输到“en_US.UTF8”,则字符将映射到 UTF-8,但它们不能由控制台正确显示。所以我写了一个小辅助函数:

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 );
}

此函数正确显示 Unicode 字符。但是,如果我使用“程序 > outfile”进行 I/O 重定向,则文件中不会写入任何内容。那么我如何检测到是否存在重定向?

标签: winapi

解决方案


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.");
}

推荐阅读