C++ stderr/stdout 重新導向到檔案,stderrstdout

來源:互聯網
上載者:User

C++ stderr/stdout 重新導向到檔案,stderrstdout
通常,stderr和stdout被用來輸出內容顯示到螢幕,但是,有時候我們需要把這些資訊寫到指定的檔案,方便隨時查閱。最簡單的實現方式就是,把 stderr/stdout 的輸出重新導向到檔案。
stderr/stdout 重新導向到檔案這裡以stderr代碼說明。

#include <stdio.h>#include <stdlib.h>int main( void ){FILE *stream = freopen( "freopen.out", "w", stderr );if( stream == NULL )fprintf( stdout, "error on freopen\n" );else{fprintf( stdout, "successfully reassigned\n" ); fflush( stdout );fprintf( stream, "This will go to the file 'freopen.out'\n" );fprintf( stderr, "Also you can do it like this!\n" );fclose( stream );}// windwos下讀取檔案 freopen.outsystem( "type freopen.out" ); getchar();return 0;}
執行結果如下,

stderr與stdout的區別stdout(標準輸出),輸出方式是行緩衝。輸出的字元會先存放在緩衝區,等按下斷行符號鍵時才進行實際的I/O操作。stderr(標準出錯),是不帶緩衝的,這使得出錯資訊可以直接儘快地顯示出來。
關於緩衝的說明:
類型 說明 輸出情況
滿緩衝 I/O操作只有在緩衝區被填滿之後才會進行 1.緩衝區滿2.刷出資料 (fflush)3.關閉檔案 (fclose)
行緩衝 通常只有遇到分行符號時,才會執行實際的I/O操作;但緩衝區滿也會強制執行 1.遇到分行符號2.緩衝區滿3.刷出資料 (fflush)4.關閉檔案 (fclose)
無緩衝 不緩衝,直接進行I/O操作 直接輸出

然而就緩衝來說,stdout與stderr沒有絕對的區別,因為緩衝類型可以設定。這裡要藉助 setvbuf() 或 setbuf() 函數。
#include <stdio.h>  #include <stdlib.h>    int main( void )  {      char buf[512] = {0};setbuf(stderr, buf);fprintf(stderr, "It is error 1\n");printf("echo 1\n");fprintf(stderr, "It is error 2\n");printf("echo 2\n");fprintf(stderr, "It is error 3\n");fflush(stderr);getchar();return 0;}  
運行結果如下:這樣,我們就可以定義緩衝區大小。緩衝區預設大小由 stdio.h 標頭檔中的宏 BUFSIZ 定義,是512位元組。另外,查閱一些資料說最小不能低於256位元組,但測試例子沒有這個問題(暫時沒有深究)。


setvbuf() 與 setbuf()setvbuf() 函數原型如下:
int setvbuf ( FILE * stream, char * buffer, int mode, size_t size );
setbuf() 可以當作是調用setvbuf(stream, buf, buf ? _IOFBF : _IONBF, BUFSIZE); 
其中, mode是聲明緩衝的類型,如下幾個:
_IOFBF 滿緩衝
_IOLBF 行緩衝
_IONBF 無緩衝
size是緩衝區大小,單位位元組。
/* setvbuf example */#include <stdio.h>int main (){  FILE *pFile=fopen ("myfile.txt","w");  setvbuf ( pFile , NULL , _IOFBF , 1024 );  // File operations here  fclose (pFile);  return 0;}


參考:http://blog.csdn.net/mycwq/article/details/46554805

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.