winapi - 如何使用 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 重定向,则文件中不会写入任何内容。那么我如何检测到是否存在重定向?
解决方案
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.");
}
推荐阅读
- python - 如何将帮助打印到标准输出?
- php - PHP 。如何在发布方法后强制我的代码重定向?
- java - 将素数添加到 X 的代码可以正常工作,但同时适用于多个测试用例,在按 Enter 之前不会执行最后一个用例
- ios - SWIFT - 如何获取表格单元格中对象的连接以从表格单元格中的另一个对象更改其属性
- javascript - 任何纠正这个/解释它的帮助将不胜感激
- python - 将pybind numpy数组从float转换为double
- php - 如果 current_time 在 A 和 B 之间,如何将自定义 CSS 代码添加到 wp_head?
- sql - 在 SQL 中组合类似的行并聚合一些值
- python - 如何使用python制作一个对数据框进行子集化的函数
- python - MagicMock 在 python 3.x 中获取数据的响应