如何在使用freopen后恢复stdout

neu*_*cer 11 c++ redirect stdout

我尝试使用以下内容从stdout重定向我的c ++程序中的输出:

 freopen(cmd.c_str(),"w",stdout);    
Run Code Online (Sandbox Code Playgroud)

然后我调用system来执行cmd.我也尝试过分叉然后调用execvp.无论哪种方式,当程序控制返回到我的程序时,写入stdout的内容不再显示.如何恢复正常行为?

Naw*_*waz 0

做这个:

fclose(stdout);
stdout = fdopen(1, "w"); //reopen: 1 is file descriptor of std output
Run Code Online (Sandbox Code Playgroud)

如果您可以使用,中的STDOUT_FILENO<unistd.h>而不是1作为 的第一个参数fdopen

  • fdopen() 失败并出现“错误文件描述符”错误,因为在调用 fclose() 后,该描述符不再存在。 (4认同)