在从 Fortran 编写的外部库中调用嘈杂的函数之前,我正在使用如下代码重定向标准输出:
// copy standard output
out = dup(STDOUT_FILENO);
// close standard output
close(STDOUT_FILENO);
// use log file as standard output
log = open(log_file, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR);
if(log != STDOUT_FILENO)
fprintf(stderr, "could not create log file %s", log_file);
// call the library function that uses a lot of printf
func();
// restore original standard output
dup2(out, STDOUT_FILENO);
// close copy of standard output
close(out);
Run Code Online (Sandbox Code Playgroud)
总结我上面代码片段的意图:复制标准输出,关闭标准输出(释放文件描述符 0),打开文件(使用最低文件描述符 = 0 = 标准输出),使用重定向标准输出运行代码,并重置标准输出。
当我使用终端作为标准输出运行我的代码时,这非常有效。但是,当我将 stdout 设置为文件(使用$ mycode > …