(This答案是基于this answer的修正版本。) 这个答案是以POSIX为中心。使用open为要重定向到的文件创建文件描述符。然后,使用dup2 to STDOUT_FILENO将stdout改为写入文件。但是,在此之前,您需要dupSTDOUT_FILENO,这样您就可以用另一个dup2恢复stdout。
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);
4条答案
按热度按时间xdnvmnnf1#
(This答案是基于this answer的修正版本。)
这个答案是以POSIX为中心。使用
open
为要重定向到的文件创建文件描述符。然后,使用dup2
toSTDOUT_FILENO
将stdout
改为写入文件。但是,在此之前,您需要dup
STDOUT_FILENO
,这样您就可以用另一个dup2
恢复stdout
。字符串
如果
funcB
正在使用std::cout
,请使用std::cout.flush()
而不是fflush(stdout)
。如果你想更直接地操作C++流,你可以使用Johnathan Wakely's answer。
wr98u20j2#
如果程序中没有其他东西使用
printf
,您可以编写自己的版本并显式链接它。如果函数已经定义,链接器将不会在标准库中查找。您可以使用vsprintf
来实现,或者使用一些更安全的带有溢出检查的版本(如果编译器提供的话)。ecbunoof3#
如果你想在
printf
上玩一个肮脏的游戏,你可以“窃取”它的输出,如下所示:字符串
您可以使用一个标志来指示如何处理您希望printf正常工作的示例。(例如,将其Map到
fprintf
或使用dlsym()
/similar来查找真实的的调用)。您还可以使用
realloc
更合理地管理缓冲区的大小。yx2lnoni4#
把
funcB
放在一个单独的程序中。然后,您可以捕获其标准输出,例如通过管道或通过将其重定向到文件。如何做到这一点通常取决于操作系统,并且超出了C的领域。或者,您可以将
funcA
进程的标准输出重定向到一个文件,然后调用FuncB
,并从该文件检索输出。同样,如何做到这一点超出了C的范围,取决于操作系统。