後如何恢復標準輸出我試着輸出在我的C++程序從標準輸出與以下重定向:使用freopen函數
freopen(cmd.c_str(),"w",stdout);
然後我打電話系統執行CMD。我也嘗試分叉,然後調用execvp。無論哪種方式,當程序控制返回到我的程序,寫入標準輸出的東西不再顯示。如何恢復正常行爲?
後如何恢復標準輸出我試着輸出在我的C++程序從標準輸出與以下重定向:使用freopen函數
freopen(cmd.c_str(),"w",stdout);
然後我打電話系統執行CMD。我也嘗試分叉,然後調用execvp。無論哪種方式,當程序控制返回到我的程序,寫入標準輸出的東西不再顯示。如何恢復正常行爲?
這樣做:
fclose(stdout);
stdout = fdopen(1, "w"); //reopen: 1 is file descriptor of std output
如果你可以使用STDOUT_FILENO從<unistd.h>
,而不是作爲1
第一個參數fdopen
。
fdopen() 「壞文件描述符」錯誤會失敗,因爲在調用fclose()之後,此描述符不再存在。 – VladV 2011-06-14 09:47:21
這裏是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;
}
.
.
}
的可能重複【如何後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