[英]How can I properly redirect C and C++ I/O to a winapi console handle?
我有一个 winapi 程序,如果使用命令行 arguments 执行,我不希望打开任何 windows。 我可以完美地附加到父控制台并且WriteConsoleA()
可以工作,但是当我尝试将 C I/O、 std::cout
和std::cin
重定向到控制台时(遵循有关此主题的几个 StackOverflow 帖子的方法) ,这些将不会按预期写入附加的控制台。
main.c -
#include <windows.h>
#include <stdio.h>
#include "cmd_line.h"
#include "dialog.h"
#include "resource.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
if(__argc > 1)
{
RedirectIOToConsole(); // Attaches and redirects
// Temporary tests
HANDLE consoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
char a[] = "hi";
WriteConsoleA(consoleOut, &a, 2, NULL, NULL); // Prints
printf("hi\n"); // Does not print
// External C++ function which performs my command line option via lots of std::cout and cin
CmdLine(__argc, __argv); // Does not print
}
else
// External C++ function to handle my winapi dialog
return DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAIN), NULL, DlgProc);
}
实现RedirectIOToConsole()
的 cmd_line.cpp 的一部分 -
void RedirectIOToConsole()
{
int hConHandle;
long lStdHandle;
FILE *fp;
AttachConsole(ATTACH_PARENT_PROCESS);
// STDOUT to the console
lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stdout = *fp;
setvbuf( stdout, NULL, _IONBF, 0 );
// STDIN to the console
lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "r" );
*stdin = *fp;
setvbuf( stdin, NULL, _IONBF, 0 );
// STDERR to the console
lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stderr = *fp;
setvbuf( stderr, NULL, _IONBF, 0 );
// C++ streams to console
std::ios_base::sync_with_stdio();
}
有人可以帮助我以正确的工作方式将stdio
和iostream
重定向到此控制台吗? 谢谢!
这应该可以,但我没有测试它:
void RedirectIOConsole()
{
freopen("CONIN$", "r", stdin);
freopen("CONOUT$", "w", stdout);
freopen("CONERR$", "w", stderr);
}
你应该使用stdout = fp;
,而不是*stdout = *fp
。 其他两个作业也一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.