我正在尝试从一个WinMain函数--一个VCL窗体应用程序--从一个控制台输送标准输出。
特别是,我需要在控制台中这样做:
mywinprogram.exe -v > toMyFile.txt
-v代表版本。传递的信息只是应用程序的版本。
我能够使用以下答案将输出送到控制台:How do I get console output in C++ with a Windows program?
但是,输出到文件的管道不起作用。
在没有任何参数的情况下启动时,应用程序的行为应该像“正常”的windows应用程序。
以这种方式获取信息的能力是用于自动构建系统的工作。
发布于 2020-02-20 22:00:19
这是我在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();
}
https://stackoverflow.com/questions/60328079
复制相似问题