Redirecting printf?

前端 未结 2 1193
猫巷女王i
猫巷女王i 2021-01-24 12:00

How do you redirect the output of printf to, for example, a stream or something? I have a gui app that links with a console library. The library makes repeated calls to printf.

相关标签:
2条回答
  • 2021-01-24 12:23

    If you want to avoid using a file you can use a named pipe, redirect stdout to it and read from it in a different thread or process.

    Some pseudocode with omitted error checking:

    HANDLE hPipe = CreateNamedPipe("\\.\pipe\SomePipeName", ...);
    int pipeFileDescriptor = _open_osfhandle(hPipe, someFlags);
    _dup2(pipeFileDescriptor, _fileno(stdout));
    

    Now what printf writes to stdout should go to the pipe.

    In another thread or process you can read from the pipe into a buffer:

    HANDLE hPipeClient = CreateFile("\\.\pipe\SomePipeName", ...);
    ReadFile(hPipeClient, ...);
    

    I think it will work but I haven't tested it yet.

    0 讨论(0)
  • 2021-01-24 12:29

    freopen(filename, mode, stdout);

    0 讨论(0)
提交回复
热议问题