C语言 如何获取printf的输出?

dy2hfwbg  于 2023-08-03  发布在  其他
关注(0)|答案(4)|浏览(151)

我从funcA调用一个函数funcBfuncB使用多个printf语句来输出数据。有没有办法通过funcA捕获这些数据?我不能修改funcB

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

funcA(){
    funcB();
}

字符串

xdnvmnnf

xdnvmnnf1#

(This答案是基于this answer的修正版本。)
这个答案是以POSIX为中心。使用open为要重定向到的文件创建文件描述符。然后,使用dup2 to STDOUT_FILENOstdout改为写入文件。但是,在此之前,您需要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);

字符串
如果funcB正在使用std::cout,请使用std::cout.flush()而不是fflush(stdout)
如果你想更直接地操作C++流,你可以使用Johnathan Wakely's answer

wr98u20j

wr98u20j2#

如果程序中没有其他东西使用printf,您可以编写自己的版本并显式链接它。如果函数已经定义,链接器将不会在标准库中查找。您可以使用vsprintf来实现,或者使用一些更安全的带有溢出检查的版本(如果编译器提供的话)。

ecbunoof

ecbunoof3#

如果你想在printf上玩一个肮脏的游戏,你可以“窃取”它的输出,如下所示:

#include <stdio.h>
#include <stdarg.h>

static char buffer[1024];
static char *next = buffer;

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

static void funcA(){
    funcB();
    // Do stuff iwth buffer here
    fprintf(stderr, "stole: %s\n", buffer);
    next=buffer; // reset for later.
}

int main() {
  funcA();
}

int printf(const char *fmt, ...) {
   va_list argp;
   va_start(argp, fmt);
   const int ret = vsnprintf(next, sizeof buffer-(next-buffer), fmt, argp);
   next += ret;
   va_end(argp);
   return ret;
}

字符串
您可以使用一个标志来指示如何处理您希望printf正常工作的示例。(例如,将其Map到fprintf或使用dlsym()/similar来查找真实的的调用)。
您还可以使用realloc更合理地管理缓冲区的大小。

yx2lnoni

yx2lnoni4#

funcB放在一个单独的程序中。然后,您可以捕获其标准输出,例如通过管道或通过将其重定向到文件。如何做到这一点通常取决于操作系统,并且超出了C的领域。
或者,您可以将funcA进程的标准输出重定向到一个文件,然后调用FuncB,并从该文件检索输出。
同样,如何做到这一点超出了C
的范围,取决于操作系统。

相关问题