das*_*ght 11
如果您无权修改打印的源代码,可以使用freopenon stdout重定向到文件:
stdout = freopen("my_log.txt", "w", stdout);
Run Code Online (Sandbox Code Playgroud)
然而,这与黑客接壤,因为命令行重定向将按预期停止工作.如果您确实可以访问执行打印的代码,fprintf则首选使用.
您也可以stdout暂时切换功能调用,然后将其恢复:
FILE *saved = stdout;
stdout = fopen("log.txt", "a");
call_function_that_prints_to_stdout();
fclose(stdout);
stdout = saved;
Run Code Online (Sandbox Code Playgroud)
这通常通过I/O重定向(...>文件)完成.
检查这个小程序:
#include <stdio.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
if (isatty (fileno (stdout)))
fprintf (stderr, "output goes to terminal\n");
else
fprintf (stderr, "output goes to file\n");
return 0;
}
ottj@NBL3-AEY55:~ $ ./x
output goes to terminal
ottj@NBL3-AEY55:~ $ ./x >yy
output goes to file
Run Code Online (Sandbox Code Playgroud)