views:

129

answers:

2

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. I need a way to intercept those and have them processed by a function. Also, creating a console is not an option. Im using Windows, btw.

Edit - Also I was hoping not to redirect to a file.

+2  A: 

freopen(filename, mode, stdout);

R Samuel Klatchko
A: 

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.

Catalin Iacob