標籤:pen 字串 test ace 定義 using lin ++ 檔案開啟
讀寫操作流程:
1.為要進行操作的檔案定義一個流對象。
2.開啟(建立)檔案。
3.進行讀寫操作。
4.關閉檔案。
詳解:
1.建立流對象:
輸入檔案流類(執行讀操作):ifstream in;
輸出檔案流類(執行寫操作):ofstream out;
輸入輸出檔案流類:fstream both;
注意:這三類檔案流類都定義在fstream中,所以只要在標頭檔中加上fstream即可。
2.使用成員函數open開啟函數:
使用方式: ios::in 以輸入方式開啟檔案(讀操作)
ios::out 以輸出方式開啟檔案(寫操作),如果已經存在此名字的檔案夾,則將其原有內容全部清除
ios::app 以輸入方式開啟檔案,寫入的資料增加至檔案末尾
ios::ate 開啟一個檔案,把檔案指標移到檔案末尾
ios::binary 以二進位方式開啟一個檔案,預設為文本開啟檔案
舉例:定義流類對象:ofstream out (輸出資料流)
進行寫操作:out.open("test.dat", ios::out); //開啟一個名為test.dat的問件
3.文字檔的讀寫:
(1)把字串 Hello World 寫入到磁碟檔案test.dat中
#include<iostream>#include<fstream>using namespace std;int main(){ ofstream fout("test.dat", ios::out); if(!fout) { cout<<"檔案開啟失敗!"<<endl; exit(1); } fout<<"Hello World"; fout.close(); return 0; } 檢查檔案test.dat會發現該檔案的內容為 Hello World
(2)把test.dat中的檔案讀出來並顯示在螢幕上
#include<iostream>#include<fstream>using namespace std;int main(){ ifstream fin("test.dat", ios::in); if(!fin) { cout<<"檔案開啟失敗!"<<endl; exit(1); } char str[50]; fin.getline(str, 50) cout<<str<<endl; fin.close(); return 0; }
4.檔案的關閉:
流對象.close(); //沒有參數
C++檔案讀寫操作