Transcript 談檔案

C++的檔案處理
2009.03 綠園
檔案的基本概念一
將一組資料儲放在記憶體上,並且給與這塊
記憶體一個名稱,就是檔案。
 檔案類型(依目的不同):程式檔、執行檔、
資料檔。
 檔案型式:

• 文字檔(text file):由文字所組成,給人們看的。
• 二進位檔(binary file):是機器碼,給電腦看的。
檔案的基本概念二

C++是以「串流」(stream)的方式來處
理輸入與輸出。為了方便串流的處理,C++
提供了 ios 類別。
(input / output stream 的縮寫)
Stream
鍵盤輸入 / 檔案
程式執行結果
讀取
input stream
output stream
寫入
由程式讀取
螢幕 / 檔案
ios 類別
ios
istream
ostream
iostream
ifstream
ofstream
fstream
可用來建立檔案物件,進行檔案處理。
需載入 #include <fstream> 標頭檔
建立檔案物件

在開啟檔案之前,必須先建立一個檔案物件
(file object)。檔案物件可分為三種:
• 可供寫入資料的檔案物件
格式:ifstream 檔案物件名稱;
例如:ifstresm infile;
• 可供讀取資料的檔案物件
格式:ofstream 檔案物件名稱;
例如:ofstresm outfile;
• 可供寫入與讀取資料的檔案物件
格式:fstream 檔案物件名稱;
例如:fstresm myfile;
檔案的開啟與關閉

開啟檔案
檔案物件.open(“檔案名稱”,ios::開啟模式);


可供選擇的開啟模式
ios::app
開啟可供附加資料的檔案
ios::in
開啟可供讀取資料的檔案
ios::out
開啟可供寫入資料的檔案
ios::trunc 若檔案已存在,先刪除它,再開啟
ios::binary 開啟二進位的輸入/輸出檔案
關閉檔案
檔案物件.close();
檔案的開啟範例
ifstream inf;
inf.open(“d:\\test.txt”, ios::in);
檢查檔案是否開啟成功
ifstream inf(“d:\\test.txt”, ios::in);
if( inf.is_open() )
{……
}
else
{……
}
檔案的關閉範例
inf.close();
文字檔的處理

將資料寫入文字檔
將資料附加到已存在的文字檔
從文字檔案讀取資料

get()、getline()、put()




利用 put() 將字串寫入檔案
文字檔的拷貝與讀取
//將資料寫入文字檔
int main()
{
ofstream ofile(“d:\\donkey.txt”, ios::out);
if(ofile.is_open())
{ ofile << “我有一隻小毛驢” << endl;
ofile << “我從來也不騎” << endl;
cout << “已將字串寫入檔案了…” << endl;
}
else
cout << “檔案開啟失敗…” << endl;
ofile.close(); //關閉檔案
return 0;
}
//將資料附加到已存在的文字檔
int main()
{
ofstream afile(“d:\\donkey.txt”, ios::app);
if(afile.is_open())
{ afile << “有一天我心血來潮騎著去趕集”;
cout << “已將字串附加到檔案了…” << endl;
}
else
cout << “檔案開啟失敗…” << endl;
afile.close();
return 0;
}
//關閉檔案
//從檔案讀取資料
int main()
{ char txt[80];
ifstream ifile(“d:\\donkey.txt”, ios::in);
if( ifile.is_open() )
while( !ifile.eof() ) //判別是否讀到檔案的尾端
{ ifile >> txt;
//將檔案內容寫入字元陣列
cout << txt << endl;
}
else
cout << “檔案開啟失敗…” << endl;
ifile.close();
return 0;
}
//關閉檔案
使用get()、getline()、put()函數
//從檔案內讀取一個字元,並把它寫入 ch 字元變數
檔案物件.get(ch);
//從檔案內最多讀取 N-1 個字元,或是讀取到 \n
//並把它存放到字串 str 中
檔案物件.getline(str, N, ’\n’);
//將ch字元變數的值寫入檔案內
檔案物件.put(ch);
//利用 put() 將字串寫入檔案
int main()
{ char txt[]=“Welcome to the C++ world”;
int i=0;
ofstream ofile(“d:\\welcome.txt”, ios::out);
if( ofile.is_open() )
{ while( txt[i] != ‘\0’ )
ofile.put(txt[i++]);
cout << “字串寫入完成…” << endl;
}
else
cout << “檔案開啟失敗…” << endl;
ofile.close();
//關閉檔案
return 0;
}
//文字檔的拷貝與讀取
int main()
{ char txt[80], ch;
ifstream ifile1(“d:\\welcome.txt”, ios::in);
ofstream ofile(“d:\\welcome2.txt”, ios::out);
while( ifile1.get(ch) )
ofile.put(ch);
cout << “拷貝完成…” << endl;
ifile1.close();
ofile.close();
ifstream ifile2(“d:\\welcome2.txt”, ios::in);
while( !ifile2.eof() )
{ ifile2.getline(txt, 80, ’\n’);
cout << txt << endl;
}
ifile2.close();
return 0;
}
【隨堂練習與回家功課】:
1.開一檔案lotto.txt,產生100組樂透號碼(01-42)。數字為1-9
者,需於前面加上0。如01~09。
2.有一資料檔案in.txt ,為一元二次方程式的係數組。內容如下:
3
1 2 1
2 3 1
3 5 2
第一行代表題數n,以下n行代表有n題的一元二次方程式係數。
請試著求解。答案顯示在螢幕上即可。
3.開一檔案magicsquare.txt,將Magic Square的輸出結果輸出
至此檔中。