本文主要是介绍C++之重定向stdout到内存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
重定向到文件比较简单
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(buffer);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/caoshangpaoutput = 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的阻塞状态,这样线程就能正常退出了。
原文链接:C++之重定向stdout到内存-CSDN博客
这篇关于C++之重定向stdout到内存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!