如何捕获printf的输出?

Gen*_*ene 7 c++ printf

我打电话的功能funcBfuncA. funcB使用几个printf语句来输出数据.有没有办法通过我捕获数据funcA?我无法修改funcB.

funcB(){
     printf( "%s", "My Name is" );
     printf( "%s", "I like ice cream" );
}

funcA(){
    funcB();
}
Run Code Online (Sandbox Code Playgroud)

jxh*_*jxh 12

这个答案是以POSIX为中心的.您可以使用open重定向dup2到文件.但是,你要STDOUT_FILENOstdout你这样做之前,这样你就可以恢复dup到类似于它与原始状态的东西STDOUT_FILENO.

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);
Run Code Online (Sandbox Code Playgroud)

对于C++流,您可以使用Johnathan Wakely的答案.