2011-05-01 86 views
11

后如何恢复标准输出我试着输出在我的C++程序从标准输出与以下重定向:使用freopen函数

freopen(cmd.c_str(),"w",stdout);  

然后我打电话系统执行CMD。我也尝试分叉,然后调用execvp。无论哪种方式,当程序控制返回到我的程序,写入标准输出的东西不再显示。如何恢复正常行为?

+0

的可能重复【如何后freopen函数(“out.txt”输出重定向到屏幕上,“一“,stdout)](http://stackoverflow.com/questions/1908687/how-to-redirect-the-output-back-to-the-screen-after-freopenout-txt-a-stdo) – sfink 2013-08-01 19:48:24

回答

1

这样做:

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

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

+2

fdopen() “坏文件描述符”错误会失败,因为在调用fclose()之后,此描述符不再存在。 – VladV 2011-06-14 09:47:21

3

这里是stdin的解决方案,如果在循环中做,需要找出一个程序,其中stdin的freopen发生在某个条件的循环中。花了一些时间,我找出(与搜索的帮助和所有),因此在这里发帖

savestdin = dup(STDIN_FILENO); 
while (1) { 
     . 
     . 
     if (inputfile) { 
       savestdin = dup(savestdin); 
       freopen(inputfile, "r", stdin); 
       restorestdin = TRUE; 
     } 
     . 
     . 
     if (restorestdin) { 
       fflush(stdin); 
       fclose(stdin); 
       stdin = fdopen(savestdin, "r"); 
       restorestdin = FALSE; 
     } 
     . 
     . 

}