C++之重定向stdout到内存

重定向到文件比较简单

freopen("text_file.txt", "w", stdout);

重定向到内存稍微复杂一点,需要借助管道,关于管道的介绍,详见:windows命名管道

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include 

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的阻塞状态,这样线程就能正常退出了。

原文链接:C++之重定向stdout到内存-CSDN博客

你可能感兴趣的:(C/C++,c++,stdout,重定向,内存,redirect,freopen,管道)