内部捕捉/重定向标准输出? [英] Internally capture/redirect stdout?

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

问题描述

这看起来有点计算系统101问题,但我很为难。

This seems like a bit of a computing systems 101 question, but I'm stumped.

我从C / C整合现有code ++项目一到我自己的项目B. A和B将被链接到一个可执行,线程的进程。项目A的code使得输出大量使用printf函数。这是好的,但我想也到输出捕捉到我自己的缓冲区。有没有一种方法,我可以从标准输出读取一次的printf调用写呢?我无法派生进程或管道。而我的努力来轮询()标准输出,或DUP()它,都没有成功(我可能是错在这里做的东西)。

I am integrating existing code from C/C++ project A into my own project B. Both A and B will be linked into a single executable, threaded process. Project A's code makes extensive use of printf for output. This is fine, but I want also to capture that output into my own buffers. Is there a way I can read from stdout once the printf calls have written to it? I cannot fork the process or pipe. And my efforts to poll() stdout, or to dup() it, have not succeeded (I may be doing something wrong here).

推荐答案

您可以使用则freopen 来改变描述符。

You can use freopen to change the descriptor.

#include<stdio.h>

main(int argc, char** argv) {
    FILE *fp = freopen("output.txt", "w", stdout);
    printf("Hello\n");
    fclose(fp);
}

如果您运行,你会看到output.txt的并没有什么与printf输出会去到你的屏幕。

If you run that you'll see the printf output in output.txt and nothing will go to your screen.

您现在可以打开读取数据文件或者你甚至可以 MMAP 它到您的存储空间和处理它的方式。

You can now open the file to read the data or you could even mmap it into your memory space and process it that way.

这篇关于内部捕捉/重定向标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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