重定向到文件比较简单
freopen("text_file.txt", "w", stdout);
重定向到内存稍微复杂一点,需要借助管道,关于管道的介绍,详见:windows命名管道
#include <thread>
#include <atomic>
#include <iostream>
#include <string>
#include <windows.h>
#include <io.h>
#include <stdio.h>
#include <fcntl.h>
#include <QDebug>
bool RedirectStdout(HANDLE &hReadPipe, HANDLE hWritePipe)
{
if (!::CreatePipe(&hReadPipe, &hWritePipe, 0, 0))
{
return false;
}
int hCrt = ::_open_osfhandle((intptr_t)hWritePipe, _O_TEXT);
FILE *hFile = ::fdopen(hCrt, "w");
*stdout = *hFile;
int ret = ::setvbuf(stdout, NULL, _IONBF, 0);
if (ret != 0)
{
return false;
}
return true;
}
std::atomic_bool runFlag(true);
int main(int argc, char *argv[])
{
HANDLE hReadPipe = INVALID_HANDLE_VALUE;
HANDLE hWritePipe = INVALID_HANDLE_VALUE;
bool ret = RedirectStdout(hReadPipe, hWritePipe);
if (ret)
{
std::thread th([&]{
const int bufferSize = 4096;
char buffer[bufferSize];
unsigned long readLength = 0;
std::string output;
while (runFlag)
{
memset(buffer, 0, bufferSize);
if (!::ReadFile(hReadPipe, buffer, bufferSize, &readLength, NULL) || !readLength)
{
runFlag = false;
break;
}
output.append(std::string(buffer, readLength);
std::string::size_type index = output.find("\r\n");
while (index != std::string::npos)
{
std::string log = output.substr(0, index) + "\r\n";
// TODO:将log添加到文本框中,会显示:
// CSDN
// 草上爬
// https://blog.csdn.net/caoshangpa
output = output.substr(index +2);
index = output.find("\r\n");
}
::CloseHandle(hReadPipe);
}
});
std::thread th2 = std::move(th);
std::cout << "CSDN" << std::endl;
std::cout << "草上爬" << std::endl;
std::cout << "https://blog.csdn.net/caoshangpa" << std::endl;
Sleep(10000);
runFlag = false;
if (hWritePipe != INVALID_HANDLE_VALUE)
{
::CloseHandle(hWritePipe);
}
if (th2.joinable())
{
th2.join();
}
// 重定向回终端
freopen("CON", "w", stdout);
std::cout << "Finished" << std::endl;
}
return 0;
}
需要注意的是,此处ReadFile为阻塞模式,管道中无数据时会阻塞等待,关闭hWritePipe会解除ReadFile的阻塞状态,这样线程就能正常退出了。文章来源:https://www.toymoban.com/news/detail-719327.html
原文链接:C++之重定向stdout到内存-CSDN博客文章来源地址https://www.toymoban.com/news/detail-719327.html
到了这里,关于C++之重定向stdout到内存的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!