天天看點

freopen()函數的用法[轉]

本文介紹如何将 stdout 重定向問題,下面純屬個人了解,如有錯誤或者不足歡迎留言交流。

函數名: freopen

功 能: 替換一個流,重定向到某個檔案,或者控制台

用 法: FILE *freopen(char *filename, char *type, FILE *stream);

緩存特征:stdin、stdout是行緩存,而stderr是無緩存的

例子:

此語句使所有的後續輸出,通常定向到轉到檔案file.txt的stdout向
           
傳回到顯示DOS視窗的的stdout向,沒這句将繼續在檔案中輸出
           

CON 是指控制台 就是DOS視窗

//程式例子
include <stdio.h>
include <stdlib.h>
void main(){
   FILE *stream ;

   if((stream = freopen("file.txt", "w", stdout)) == NULL)
   //将内容寫到file.txt
       exit(-);   
   printf("this is stdout output\n"); 

   if((stream = freopen("CON", "w", stdout)) == NULL)
   //stdout 是向程式的末尾的控制台重定向
       exit(-);    
   printf("And now back to the console once again\n");

    return ;
}
           

連結:https://zhidao.baidu.com/question/119566646.html?fr=qrl&index=0&qbl=topic_question_0&word=freopen