如何捕获printf的输出? [英] How to capture output of printf?
问题描述
我正在从 funcA
调用函数 funcB
。
funcB
使用多个 printf
语句输出数据。
我是否可以通过 funcA
捕获数据?
我无法修改 funcB
。
I am calling a function funcB
from funcA
.
funcB
uses several printf
statements to output data.
Is there a way for me to capture that data via funcA
?
I can not modify funcB
.
funcB(){
printf( "%s", "My Name is" );
printf( "%s", "I like ice cream" );
}
funcA(){
funcB();
}
推荐答案
(此答案已更正版本基于此答案。)
(This answer is a corrected version based on this answer.)
此答案是POSIX中心使用 open
为要重定向到的文件创建文件描述符。然后,使用 dup2
到 STDOUT_FILENO
更改 stdout
来写改为文件。但是,在执行此操作之前,您需要 dup
STDOUT_FILENO
,以便可以还原 stdout
和另一个 dup2
。
This answer is POSIX centric. Use open
to create a file descriptor for the file you want to redirect to. Then, use dup2
to STDOUT_FILENO
to change stdout
to write to the file instead. But, you'll want to dup
the STDOUT_FILENO
before you do that, so you can restore stdout
with another dup2
.
fflush(stdout);
int stdout_fd = dup(STDOUT_FILENO);
int redir_fd = open(redirected_filename, O_WRONLY);
dup2(redir_fd, STDOUT_FILENO);
close(redir_fd);
funcB();
fflush(stdout);
dup2(stdout_fd, STDOUT_FILENO);
close(stdout_fd);
如果 funcB
正在使用 std :: cout
,使用 std :: cout.flush()
代替 fflush(stdout)
。
If funcB
is using std::cout
, use std::cout.flush()
instead of fflush(stdout)
.
如果您想更直接地操作C ++流,可以使用 Johnathan Wakely的答案。
If you want to manipulate C++ streams more directly, you can use Johnathan Wakely's answer.
这篇关于如何捕获printf的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!