C語言文件操作函數(shù)freopen詳細解析
今天做USACO 用到了文件的操作。 之前做USACO只是格式化的些 寫 freopen("xxx.in","r",stdin) 和"freopen("xxx.out","w",stdout)"
百度百科上是這么介紹的:
函數(shù)名: freopen
功 能: 替換一個流,或者說重新分配文件指針,實現(xiàn)重定向。如果stream流已經(jīng)打開,則先關閉該流。如果該流已經(jīng)定向,則freopen將會清除該定向。此函數(shù)一般用于將一個指定的文件打開一個預定義的流:標準輸入、標準輸出或者標準出錯。
用 法: FILE *freopen(const char *filename,const char *type, FILE *stream);
頭文件:stdio.h
例1:
#include <stdio.h>
#include <stdlib.h>
int main()
{
if(freopen("file.txt","w",stdout)==NULL)
fprintf(stderr,"error\n");
printf("This is in the file\n"); //這句話會在file.txt中顯示。
fclose(stdout); //使用fclose()函數(shù)就可以把<A target=_blank>緩沖區(qū)</A>內(nèi)最后剩余的數(shù)據(jù)輸出到磁盤文件中,并釋放文件指針和有關的緩沖區(qū)。
return 0;
}
例2:
//首先在同路徑下創(chuàng)建一個in.txt文本文檔寫入若干數(shù)字
#include <stdio.h>
#include <stdlib.h>
int main()
{
freopen("in.txt","r",stdin); //從in.txt 中讀入數(shù)據(jù)
freopen("out.txt","w",stdout); // 將最后數(shù)據(jù)寫入out.txt中
int a,b;
while(scanf("%d%d",&a,&b)!=EOF) //數(shù)據(jù)是從in.txt中輸入的
printf("%d\n",a+b); //寫入out.txt中
fclose(stdin);
fclose(stdout);
return 0;
}
freopen("CON","w",stdout) 表示在控制臺窗口上寫入數(shù)據(jù);
例3:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// FILE *stream;
freopen("file1.txt","w",stdout);
printf("this is in file1.txt"); // 這句話在file1.txt中顯示
freopen("CON","w",stdout);
printf("And this is in command.\n"); //這句話在控制臺上顯示
return 0;
}
例5: 關于fread 可以通過下面的程序,一看就知道什么意思了
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *stream
char s[102400]="";
if((stream=freopen("file.txt","r",stdin))==null)
exit(-1);
fread(s,1,1024,stdin); // 讀取file.txt中1到1024位,放入s中 ,我是這么理解的
printf("%s\n",s);
return 0;
}
您可能感興趣的文章
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用函數(shù)刪除字符
- 04-02c語言的正則匹配函數(shù) c語言正則表達式函數(shù)庫
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言中對數(shù)函數(shù)的表達式 c語言中對數(shù)怎么表達
- 04-02c語言用函數(shù)寫分段 用c語言表示分段函數(shù)
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排序法函數(shù)
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段函數(shù)
- 04-02C語言中怎么打出三角函數(shù) c語言中怎么打出三角函數(shù)的值
- 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求階乘


閱讀排行
本欄相關
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對數(shù)函數(shù)的表達式 c語言中對
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求
隨機閱讀
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 04-02jquery與jsp,用jquery
- 01-10C#中split用法實例總結(jié)
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-11ajax實現(xiàn)頁面的局部加載
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 01-10SublimeText編譯C開發(fā)環(huán)境設置
- 01-10delphi制作wav文件的方法