我正在尝试通过控制台通过VCL表单应用程序通过WinMain函数传递标准输出。
特别是,我需要在控制台中执行此操作:
mywinprogram.exe -v > toMyFile.txt
-v代表版本。传递的信息只是应用程序的版本。
我可以使用以下答案将结果输出到控制台 : How do I get console output in C++ with a Windows program?
但是将输出管道传输到文件不起作用。
在不带任何参数的情况下启动时,该应用程序的行为应类似于“正常”的Windows应用程序。
以这种方式获取信息的能力是针对自动构建系统的。
答案 0 :(得分:0)
这是我在Sev的答案中找到的版本。
首先要做的就是调用此函数。_tWinMain()
:
#include <cstdio>
#include <fcntl.h>
#include <io.h>
void RedirectIOToConsole() {
if (AttachConsole(ATTACH_PARENT_PROCESS)==false) return;
HANDLE ConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
int SystemOutput = _open_osfhandle(intptr_t(ConsoleOutput), _O_TEXT);
// check if output is a console and not redirected to a file
if(isatty(SystemOutput)==false) return; // return if it's not a TTY
FILE *COutputHandle = _fdopen(SystemOutput, "w");
// Get STDERR handle
HANDLE ConsoleError = GetStdHandle(STD_ERROR_HANDLE);
int SystemError = _open_osfhandle(intptr_t(ConsoleError), _O_TEXT);
FILE *CErrorHandle = _fdopen(SystemError, "w");
// Get STDIN handle
HANDLE ConsoleInput = GetStdHandle(STD_INPUT_HANDLE);
int SystemInput = _open_osfhandle(intptr_t(ConsoleInput), _O_TEXT);
FILE *CInputHandle = _fdopen(SystemInput, "r");
//make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog point to console as well
ios::sync_with_stdio(true);
// Redirect the CRT standard input, output, and error handles to the console
freopen_s(&CInputHandle, "CONIN$", "r", stdin);
freopen_s(&COutputHandle, "CONOUT$", "w", stdout);
freopen_s(&CErrorHandle, "CONOUT$", "w", stderr);
//Clear the error state for each of the C++ standard stream objects.
std::wcout.clear();
std::cout.clear();
std::wcerr.clear();
std::cerr.clear();
std::wcin.clear();
std::cin.clear();
}