第十二章 资料流与档案的存取.docx
《第十二章 资料流与档案的存取.docx》由会员分享,可在线阅读,更多相关《第十二章 资料流与档案的存取.docx(14页珍藏版)》请在冰点文库上搜索。
第十二章资料流与档案的存取
第十二章資料流與檔案的存取
12-1DataStream
以往所敎的資料輸入與資料輸出,係由下述兩項資料流所構成
cin–inputstreamobjcet
cout–outputstreamobject
其硬體之溝通方式如下
12-2檔案存取
步驟:
1.加入fstream–filestreamheaderfile
#include
usingstd:
:
ifstream;
usingstd:
:
ofstream;
2.//宣告檔名
char*FileNameIn="Incom.txt";
char*FileNameOut="Tax.txt";
3.輸入型檔案資料流(inputfilestream)
ifstreamFileInput;//inputfilestream
上行中FileInput為連結檔案的資料流名稱
4.輸出型檔案資料流(outputfilestream)
ofstreamFileOutput;//outputfilestream
上行中FileOutput為連結檔案的資料流名稱
5.開啟檔案
FileInput.open(FileNameIn);//開啟輸入檔
FileOutput.open(FileNameOut);//開啟輸出檔
6.進行輸出與輸入動作
7.關閉檔案
FileInput.close();//開啟輸入檔
FileOutput.close();//開啟輸出檔
補充:
物件導向之基本語法→簡略介紹「呼叫成員函數」
類別(class)內部所定義之各種函數稱為成員(members)或者方法(methods)
如果要取用類別裡面的成員,則需要用到成員運算子(memberoperator)「.」
Example:
charch;→charch;
cin>>ch;→cin.get(ch);
「.」句點稱為成員運算子符號(memberoperator)
cin.get(ch);
cin→物件名稱,get()→成員函數名稱,ch→參數
注意:
使用成員函數必須在它的前面寫出所附屬物件名稱
故ifstreamFileInput;//定義FileInput物件
FileInput.open(FileNameIn);//open為成員函數名稱
FileInput.close();//close為成員函數名稱
練習1.先開啟一個文字檔案,編輯以下內容,內容為:
學號成績
0012325
0012430
0012590
00127100
再存檔為student.txt
隨後讀入程式,進行平均分數及找出最高最低分,其結果存檔成grade.txt,輸出的內容為
Average=Ave
Max=Max
Min=Min
其中Ave、Max及Min為實際計算結果所得到的成績
程式重點:
1.檔案輸入名稱/輸出名稱宣告
2.輸入檔案名稱
3.開啟檔案,失敗時錯誤訊息說明
4.輸入檔案讀取
5.輸出檔案格式
6.檔案關閉
12-3檔案的存取模式
1、檔案存在與否
不存在→create創造
存在→replace取代或append附加,使檔案變大
2、使用modeindicator進行檔案之處理,包含下列參數
modeindicator
Fileopenmode
ios:
:
in
inputformat
ios:
:
out
outputformat
ios:
:
app
appendformat
ios:
:
ate
atendformat
ios:
:
binary
binaryformat
ios:
:
trunc
truncationformat
ios:
:
nocreate
iffiledon’texist,itcannotbecreated
ios:
:
noreplace
iffileexist,itcannotbereplaced
3、用法
Example1.原本開啟指令
fileinput.open(inputfile);
if(!
fileinput)
{
cout<<"Openfilename"<exit
(1);
}
程式可以改成如下
fileinput.open(inputfile,ios:
:
nocreate);//只開啟舊檔
if(!
fileinput.fail())
{
cout<<"Openfilename"<exit
(1);
}
Example2.使用fstreamclass
前一節之使用模式
ifstreamFileInput;
ofstreamFileOutput;
統一使用fstreamclass,再於modeindicator中指定
片段程式如下:
fstreamFileInput;
fstreamFileOutput;
FileInput.open(FileNameIn,ios:
:
in);
FileOutput.open(FileNameOut,ios:
:
out);
也可以寫成如下:
FileInput.open(FileNameIn,ios:
:
in|ios:
:
nocreate);
12-4如何找尋資料終點(EndofFile)
C++使用標頭檔fstream內定義的常數EOF(EndOfFile)表示資料檔結束,相當於字串結束符號'\0'
實例程式練習:
撰寫一個程式,能夠讀入一組英文字母字串,再將其中小寫英文字母轉換成大寫字母
1.載入標頭檔
#include
usingstd:
:
cin;
usingstd:
:
cout;
usingstd:
:
endl;
#include
#include
usingstd:
:
fstream;
usingstd:
:
ios;
2.宣告排序與轉換大寫之函數
intSort(char);
3.主程式
intmain()
{
//宣告字元
charc;
//宣告輸入的檔案檔名
char*filenamein="Smell.txt";
char*filenameout="Big.txt";
//開啟輸入的檔案
fstreamfileinput(filenamein,ios:
:
in);
if(!
fileinput){
cout<<"Openfilename:
"<<exit
(1);
}
//開啟輸出的檔案
fstreamfileoutput(filenameout,ios:
:
out);
if(!
fileoutput){
cout<<"Filename:
"<<exit
(1);
}
//進行檔案檢查與大小寫轉換
while((c=fileinput.get())!
=EOF)//將c與EOF比對
{
switch(Sort(c))
{
case1:
fileoutput<break;
case0:
case2:
case3:
case4:
fileoutput<break;
case5:
fileoutput<<"Other.";
break;
default:
cout<<"Programneverarrivehere."<}
}
fileoutput.close();
fileinput.close();
cout<<"Thefilehassavedinto"<<<"successfully."<return0;
}
//定義轉換大小寫之函數
intSort(charx){
if(isupper(x))
return0;
elseif(islower(x))
return1;
elseif(isdigit(x))
return2;
elseif(isspace(x))
return3;
elseif(ispunct(x))//標點符號
return4;
else
return5;
}
12-5資料的讀取和寫入
假設下列型態
charch;
char*S1;
intN;
下列fstream之成員函數可以進行檔案處理
memberfuction
usage
get(ch)
inputacharfrominputfilestream
getline(S1,N,'\n')
inputacharfrominputfilestreamuntil(N-1)charor'\n',andsaveintostringS1.
peek()
checknextcharininputfilestream
put(ch)
putacharintooutputfilestream
putback(ch)
putacharintoinputfilestream
eof()
ifthemotionofinputexceedsendoffile,return"true"
ignore(N)
ignorenextNchar
範例程式:
使用peek()來檢查即將讀入的字元是否為EOF,如果尚未達到檔案的結尾,就繼續讀入資料,讀入人名、學號與成績,將成績開根號乘以十,再存成另一個檔案
程式說明:
1.先將標頭檔載入與建立輸入/輸出檔案檔名
#include
usingstd:
:
cin;
usingstd:
:
cout;
usingstd:
:
endl;
#include
#include
usingstd:
:
fstream;
usingstd:
:
ios;
#include
usingstd:
:
setw;
char*FileNameIn="Record.txt";
char*FileNameOut="Save.txt";
2.主程式
intmain()
{
//建立輸入陣列
constintMaxNum=50;
constintMaxSize=20;
charName[MaxNum][MaxSize];//名字陣列
intScore[MaxNum];//成績陣列
intStdNum[MaxNum];//學號陣列
//開啟輸入檔案
fstreamFileInput(FileNameIn,ios:
:
in);
if(!
FileInput)
{
cout<<"Filename:
"<exit
(1);
}
//開啟輸出檔案
fstreamFileOutput(FileNameOut,ios:
:
out);
if(!
FileOutput)
{
cout<<"Filename:
"<exit
(1);
}
//讀入資料檔案,並計算成績
intcount=0;//計數器
while(FileInput.peek()!
=EOF&&count{
FileInput>>Name[count]>>StdNum[count]>>Score[count];
count++;
}
for(inti=0;i{
Score[i]=sqrt(Score[i])*10.0;
FileOutput<<<<}
FileOutput.close();
FileInput.close();
cout<<"Inputfilehastranslateto"<return0;
}
附註:
為防止輸入檔案Record.txt多了幾個'\n'字元,可將程式改成如下
intcount=0;
while(count{
if(FileInput.peek()==EOF)
break;
FileInput>>Name[count]>>StdNum[count]>>Score[count];
FileInput.ignore();
if(FileInput.peek()=='\n')
{
count++;
break;
}
count++;
}
12-6FilePositionMarker
用途:
可以找尋檔案內部資料任意位置
使用:
位置標記有三種模式(modesofthefilepositionmarker)
ios:
:
beg;//filebegining
ios:
:
cur;//filecurrentposition
ios:
:
end;//fileend
配合四種filestream之成員函數使用
memberfuction
usage
seekg(offset,mode)
從輸入檔案中,依mode所規定之起點,移到偏移量所規定的位置
seekp(offset,mode)
從輸出檔案中,依mode所規定之起點,移到偏移量所規定的位置
tellg()
在輸入檔案中,獲得字元數目到目前所在標記位置
tellp()
在輸出檔案中,獲得字元數目到目前所在標記位置
說明:
offset及mode的資料型態為longint,g代表get,p代表put
實例之片段程式:
1.FileOutput.seekp(5L,ios:
:
cur);
將輸出檔案中的位置標記從目前所在位置往前移動5個字元的距離
2.FileOutput.seekp(2L,ios:
:
beg);
將輸出檔案中的位置標記從檔案開始移到第3個字元
3.FileOutput.seekp(-5L,ios:
:
end);
將輸出檔案中的位置標記移到倒數第5個字元
4.FileInput.seekg(0L,ios:
:
beg);
將輸入檔案中的位置標記移到檔案開頭
5.FileInput.seekg(0L,ios:
:
end);
將輸入檔案中的位置標記移到檔案結尾
6.tellg()之應用
i.從已完成連結的檔案資料流中獲得檔案中的字元數目
Example:
ifstreamFileInput("Data.txt");//Openfile"Data.txt"
longCharNum;//宣告CharNum為longinteger
FileInput.seekg(0L,ios:
:
end);//移到檔案結束處
CharNum=FileInput.tellg();//獲得字元數目
ii.將既有的檔案中字元次序顛倒過來
Example:
(接上例)
longOffset;
charCh;
for(Offset=1L;Offset<=CharNum;Offset++)
{
FileInput.seekg(-Offset,ios:
:
end);
Ch=FileInput.get();
FileOutput<}
練習:
讀入一篇英文文章,然後以相反次序將文章印出來,並且另存
********************************************************************************
第十二章作業
*******************************************************************************
1.一個程式,能將任何檔案中的空白字元及跳行字元’\n’去除,並存到另一個檔案中。
2.已知資管系學生成績資料檔案格式名稱為student.txt,其格式如下
學號姓名成績
123王大呆60
………
老師想要得到所有學生之平均成績、最高分及最低分,並統計不及格人數,同時這些資料要輸出成為一個檔案。
請撰寫之。
(存取時使用ifstream及ofstream)
3.王老五參加我愛紅娘活動,活動辦法是有一組相同人數之男士與女士,經由亂數配對後再進行見面聯誼,請設計此亂數配對程式,其中男士與女士人數可任意設定,且各不超過100人,且男士與女士各有檔案格式如下:
Man_IDName
001王小呆
……..
配對後之檔案請另存新檔。
(存取時使用fstream)
4.寫一個程式,能讀入一個中文檔案,然後將檔案倒過來,並存到另一個檔案中。
1.撰寫一個程式,使其能夠完成下列功能:
(a)建立一個日期結構,其結構欄位包括日、月及年。
(b)由鍵盤輸入值,並將值指定給該結構存放。
(c)以mm/dd/yyyy的格式印出結構值,mm代表月,有兩格;dd代表日,有兩格,yyyy代表年,有四格,例如06/18/2000。