重定向printf? [英] Redirecting printf?

查看:40
本文介绍了重定向printf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何将 printf 的输出重定向到例如流或其他内容?我有一个与控制台库链接的 gui 应用程序.库重复调用 printf.我需要一种方法来拦截它们并让它们由函数处理.此外,创建控制台不是一种选择.顺便说一句,我使用的是 Windows.

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.

推荐答案

如果您想避免使用文件,您可以使用命名管道,将标准输出重定向到它并在不同的线程或进程中读取它.

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));

现在 printf 写入 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.

这篇关于重定向printf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆