C語言文件操作函數(shù)freopen詳細(xì)解析
今天做USACO 用到了文件的操作。 之前做USACO只是格式化的些 寫 freopen("xxx.in","r",stdin) 和"freopen("xxx.out","w",stdout)"
百度百科上是這么介紹的:
函數(shù)名: freopen
功 能: 替換一個流,或者說重新分配文件指針,實現(xiàn)重定向。如果stream流已經(jīng)打開,則先關(guān)閉該流。如果該流已經(jīng)定向,則freopen將會清除該定向。此函數(shù)一般用于將一個指定的文件打開一個預(yù)定義的流:標(biāo)準(zhǔn)輸入、標(biāo)準(zhǔn)輸出或者標(biāo)準(zhǔn)出錯。
用 法: 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ù)輸出到磁盤文件中,并釋放文件指針和有關(guān)的緩沖區(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: 關(guān)于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;
}
相關(guān)文章
C語言實現(xiàn)航班售票系統(tǒng) C語言實現(xiàn)航班管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語言實現(xiàn)航班售票系統(tǒng),C語言實現(xiàn)航班管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-12-12C++ 中約瑟夫環(huán)替換計數(shù)器m(數(shù)組解決)
這篇文章主要介紹了C++ 中約瑟夫環(huán)替換計數(shù)器m(數(shù)組解決)的相關(guān)資料,需要的朋友可以參考下2017-05-05詳解在C++中顯式默認(rèn)設(shè)置的函數(shù)和已刪除的函數(shù)的方法
這篇文章主要介紹了在C++中顯式默認(rèn)設(shè)置的函數(shù)和已刪除的函數(shù)的方法,文中講到了C++11標(biāo)準(zhǔn)中的新特性,需要的朋友可以參考下2016-01-01Visual Studio 2019安裝、測試創(chuàng)建c語言項目(圖文教程)
這篇文章主要介紹了Visual Studio 2019安裝、測試創(chuàng)建c語言項目,Visual Studio 2019是完全免費的,而且安裝比較簡單,現(xiàn)在把安裝步驟分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2020-03-03