Home How to redirect std::cout and printf in windows
Reply: 0

How to redirect std::cout and printf in windows

user2757 Published in June 20, 2018, 1:20 am

i have created program based on this article Creating a Child Process with Redirected Input and Output, but it doesn't work std::cout and printf, so from program like this i got ony "Hello, momma" string and nothing came from cout and printf parts:

int _tmain(int argc, _TCHAR* argv[])
    HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);

    const char *buffer = "Hello, momma";

    std::cout << buffer << " - iostream version\n";

    printf("%s - stdio version", buffer);

    DWORD dwWritten = 0;
    WriteFile(hStdOut, buffer, strlen(buffer), &dwWritten, NULL);

    return 0;

Q: How can i intercept cout and printf? I have no access to source code of child program, i just need to intercept its output.

This is the output if run only child process:

Hello, momma - iostream version

Hello, momma - stdio versionHello, momma

so, as you can see, all three versions are printed.

As requested code of parent program:

void RedirectIO(HANDLE &hRead, HANDLE &hWrite)
    ZeroMemory(&attr, sizeof(attr));
    attr.nLength = sizeof(attr);
    attr.bInheritHandle = true;

    CreatePipe(&hRead, &hWrite, &attr, 0);
    SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0);

bool CreateChild(std::string CommandLine, DWORD WaitTime, HANDLE hInRead, HANDLE hOutWrite)
    ZeroMemory(&SI, sizeof(SI));
    ZeroMemory(&PI, sizeof(PI));

    SI.cb = sizeof(SI);
    SI.hStdError = hOutWrite;
    SI.hStdInput = hInRead;
    SI.hStdOutput = hOutWrite;

    bool success = CreateProcess(0, const_cast<char*>(CommandLine.c_str()), 0, 0, true, NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW, 0, 0, &SI,&PI);

    if (success)
        WaitForSingleObject(PI.hProcess, WaitTime);

    return success;

int main()
    HANDLE hRead = nullptr;
    HANDLE hWrite = nullptr;

    RedirectIO(hRead, hWrite);
    CreateChild("stdouterrin.exe", INFINITE, nullptr, hWrite);

    DWORD ReadCount = 0;
    char Buffer[1024] = {0};

    std::string data = std::string();

        if (!ReadFile(hRead, Buffer, sizeof(Buffer) / sizeof(char), &ReadCount, 0))

        if (!ReadCount) break;

        Buffer[ReadCount] = '\0';
        data.append(&Buffer[0], ReadCount);
        std::cout<<"Read From Child:\n\n"<<data.c_str()<<"\n";

    return 0;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.31315 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO