为什么我不能重定向WriteConsole的输出? [英] Why can't I redirect output from WriteConsole?
问题描述
在以下程序中,我使用两种不同的功能打印到控制台
In the following program I print to the console using two different functions
#include <windows.h>
int main() {
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD byteswritten;
WriteConsole(h, "WriteConsole", 12, &byteswritten, NULL);
WriteFile(h, "WriteFile", 9, &byteswritten, NULL);
}
如果我执行此程序并使用 a>重定向它的输出,out.txt
或 a 1>out.txt
没有任何内容打印到控制台(按预期),但是 out.txt
的内容仅为
If when I execute this program and redirect it's output using a > out.txt
or a 1> out.txt
nothing gets printed to the console (as expected) but the contents of out.txt
are only
WriteFile
两者之间的不同之处在于,它们允许将对 WriteFile
的调用重定向到该文件,并将对 WriteConsole
的调用转到...无处
What is different between the two that allows calls to WriteFile
to be redirected to the file and calls to WriteConsole
to go to ... nowhere
在Windows 10上使用gcc和msvc进行了测试
Tested with gcc and msvc on windows 10
推荐答案
WriteConsole
仅适用于控制台屏幕手柄,不适用于文件或管道.
WriteConsole
only works with console screen handles, not files nor pipes.
如果仅编写ASCII内容,则可以使用 WriteFile
进行所有操作.
If you are only writing ASCII content you can use WriteFile
for everything.
如果您需要编写Unicode字符,则可以使用 GetConsoleMode 代码>
来检测句柄类型,对于不是控制台句柄的所有内容,它都会失败.
If you need to write Unicode characters you can use GetConsoleMode
to detect the handle type, it fails for everything that is not a console handle.
在进行这样的原始输出时,如果句柄是,则还必须处理 BOM 重定向到文件.
When doing raw output like this you also have to deal with the BOM if the handle is redirected to a file.
此博客文章是一个很好的起点在Windows控制台中处理Unicode ...
This blog post is a good starting point for dealing with Unicode in the Windows console...
这篇关于为什么我不能重定向WriteConsole的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!