讀寫操作流程:
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(); //沒有參數
