重定向stdout到檔案

2021-09-01 22:39:51 字數 1076 閱讀 8495

把stdout重定向到檔案

兩種方法:

第一種方法沒有恢復

通過freopen把stdout重新開啟到檔案

#include

file *stream;

void main( void )

fprintf( stdout, "this is not print out\n" );//這裡沒有輸出

//system( "ls" );//沒有會造成問題,需要小心

}

輸出結果

[img]

----------------------

第二種方法使用dup複製

先把 1 複製出來

然後建立個檔案,用fileno取到檔案描述符 覆蓋到1

所有對1的操作都輸出到檔案了

用完之後,再把開始複製出來的 用dup2還給 1

#include

#include

#include

int main( )

write( old, "this goes to stdout first\r\n", 27 );

if( ( new = fopen( "data", "w" ) ) == null )

if( -1 == dup2( fileno( new ), 1 ) )//把檔案的描述符給到1,1就不代表stdout了

system( "ls -l" );

puts( "this goes to file 'data'\r\n" );

fflush( stdout );

fclose( new );

dup2( old, 1 ); // 恢復

puts( "this goes to stdout\n" );

puts( "the file 'data' contains:" );

//system( "type data" );

system( "file data" );

}

輸出結果

[img]

本程序stdout重定向到管道 以及恢復

接管stdout輸出,重定向到指定管道,不需要的時候則恢復。建立管道,通過微軟的dup儲存預設stdout,dup2介面重定向,再通過 dup2恢復回來。參考以下 int hstdout int hstdoutpipe 2 if pipe hstdoutpipe,out buff size,o bi...

Cout重定向到檔案

cout預設是與監視器 螢幕 相連,cout出來的內容會輸出到螢幕上,通常是會在命令列視窗之中。但有時,我們希望將cout出來的具體日誌 錯誤資訊寫到某個檔案之中,而螢幕上僅僅顯示出當前進行的任務,以及程式執行狀態等資訊。我們可以使用下面重定向的方式來實現 cpp view plain copy i...

C stderr stdout 重定向到檔案

通常,stderr和stdout被用來輸出內容顯示到螢幕,但是,有時候我們需要把這些資訊寫到指定的檔案,方便隨時查閱。最簡單的實現方式就是,把 stderr stdout 的輸出 重定向到檔案。這裡以stderr 說明。include include int main void windwos下讀取...