當前位置:才華齋>計算機>C語言>

C語言檔案操作函式freopen詳解

C語言 閱讀(1.97W)

今天做USACO 用到了檔案的操作。 之前做USACO只是格式化的.些 寫 freopen("","r",stdin) 和"freopen("","w",stdout)"

C語言檔案操作函式freopen詳解

百度百科上是這麼介紹的:

函式名: freopen

功 能: 替換一個流,或者說重新分配檔案指標,實現重定向。如果stream流已經開啟,則先關閉該流。如果該流已經定向,則freopen將會清除該定向。此函式一般用於將一個指定的檔案開啟一個預定義的流:標準輸入、標準輸出或者標準出錯。

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

標頭檔案:stdio.h

例1:

複製程式碼 程式碼如下:

#include

#include

int main()

{

if(freopen("","w",stdout)==NULL)

fprintf(stderr,"errorn");

printf("This is in the filen"); //這句話會在中顯示。

fclose(stdout); //使用fclose()函式就可以把緩衝區內最後剩餘的資料輸出到磁碟檔案中,並釋放檔案指標和有關的緩衝區。

return 0;

}

例2:

複製程式碼 程式碼如下:

//首先在同路徑下建立一個文字文件寫入若干數字

#include

#include

int main()

{

freopen("","r",stdin); //從 中讀入資料

freopen("","w",stdout); // 將最後資料寫入中

int a,b;

while(scanf("%d%d",&a,&b)!=EOF) //資料是從中輸入的

printf("%dn",a+b); //寫入中

fclose(stdin);

fclose(stdout);

return 0;

}

freopen("CON","w",stdout) 表示在控制檯視窗上寫入資料;

例3:

複製程式碼 程式碼如下:

#include

#include

int main()

{

// FILE *stream;

freopen("","w",stdout);

printf("this is in "); // 這句話在中顯示

freopen("CON","w",stdout);

printf("And this is in command.n"); //這句話在控制檯上顯示

return 0;

}

例5: 關於fread 可以通過下面的程式,一看就知道什麼意思了

複製程式碼 程式碼如下:

#include

#include

int main()

{

FILE *stream

char s[102400]="";

if((stream=freopen("","r",stdin))==null)

exit(-1);

fread(s,1,1024,stdin); // 讀取中1到1024位,放入s中 ,我是這麼理解的

printf("%sn",s);

return 0;

}