iostream標準庫提供了cin和cout方法用于標準輸入讀取流和向標準輸出寫入流。
從文件讀取流和向文件寫入流,需要用到fstream庫。它定了三個數據類型
數據類型 | 描述 |
ofstream | 該數據類型表示輸出文件流,用于創建文件并向文件寫入信息 |
ifstream | 該數據類型表示輸入文件流,用于從文件讀取信息 |
fstream | 該數據類型通常表示文件流,同時具有ofstream和ifstream兩種功能,這意味著它可以創建文件,從文件中讀取信息,向文件寫入信息 |
在C++中進行文件處理,必須在C++源代碼文件中包含頭文件<iostream>和<fstream>
?
打開文件
在從文件讀取信息或向文件寫入信息之前,必須先打開文件。ofstream和fstream對象都可以用來打開文件進行寫操作,如果只需要打開文件進行對文件,則使用ifstream對象。
下面是open()函數的標準語法,open()函數是fstream、ifstream、ofstream對象的一個成員。
void open(const char *filename,ios::openmode mode);
在這里open()成員函數的第一個參數指定要打開的文件的名稱和位置,第二個參數定義文件被打開的模式。
模式標志 | 描述 |
ios::app | 追加模式,文件寫入都追加到文件末尾 |
ios::ate | 文件打開后定位到文件末尾 |
ios::in | 打開文件用于讀取 |
ios::out | 打開文件用于寫入 |
ios::trunc | 如果該文件已經存在,其內容將在打開文件之前被階段,即把文件長度設置為0 |
上面兩種或兩種以上的模式結合使用。
例如想要以寫入模式打開文件,并希望以寫入模式打開文件,并希望截斷文件,以防文件已存在,那么可以說使用以下語法:
ofstream outline;
outline.open(“file.dat”,ios::out | ios::trunc);
?
如果想要打開一個文件用于讀寫,可以使用以下語法:
ifstream afile;
afile.open(“file.dat”,ios::out | ios:: in);
?
關閉文件
當C++程序終止時,它會自動關閉刷新所有流,釋放所有分配的內存,并關閉所有打開的文件。但程序員應該養成一個好習慣,在程序終止前關閉所有打開的文件。
close()函數時fstream、ifstream和ofstream對象的一個成員
void close();
?
寫入文件
在C++編程中,我們使用流插入符(<<) 向文件寫入信息,就像使用該運算符輸出信息到屏幕上一樣。唯一不同的是,在這里使用的是ofstream或fstream對象,而不是cout對象。
讀取文件
在C++編程中,我們使用流插入符(>>) 向文件讀取信息,就像使用該運算符輸出信息到屏幕上一樣。唯一不同的是,在這里使用的是ofstream或fstream對象,而不是cin對象。
?
/*** afile.cpp ***/ #include<iostream> #include<fstream> using namespace std;int main() {char data[100];//open file with write mode ofstream outfile;outfile.open("afile.dat");cout << "Write to the file" << endl;cout << "Enter your name: ";cin.getline(data,100);//write data of user inout to fileoutfile << data << endl;cout << "Enter you age: ";cin >> data;cin.ignore();//write data to file againoutfile << data << endl;//close the file outfile.close();//open file with read mode ifstream infile;infile.open("afile.dat");cout << "Reading from the file " << endl;infile >> data;//write data in screencout << data << endl;//read data from file again and show it in screeninfile >> data;cout << data << endl;//close the reading file infile.close();return 0; }
運行結果:
exbot@ubuntu:~/wangqinghe/C++/20190813$ g++ afile.cpp -o afile
exbot@ubuntu:~/wangqinghe/C++/20190813$ ./afile
Write to the file
Enter your name: wangqinghe
Enter you age: 25
Reading from the file
wangqinghe
25
?
上面的實例使用了cin對象的附件函數,比如getline()從外部讀取一行,ignore()函數會忽略掉之前讀語句留下的多余字符。
?
文件位置指針
istream和ostream都提供了用于重新定位文件位置指針的成員函數。這些成員函數包括istream的seekg(“seek get”)和關于ostream的seekp(“seek put”)。
seekg和seekp的參數通常是一個長整型,第二個參數可以用于指定查找方向。查找方向可以是iOS::beg(默認從流的開頭開始定位),也可以是ios::cur(從流的當前位置開始定位),也可以是ios::end(從流的末尾開始定位)。
文件位置指針是一個整數值,指定了從文件起始位置到文件所在位置的字節數。
//定位到fileObject的第n個字節(假定是iOS::beg) fileObject.seekg(n);//把文件的讀指針從fileObject從當前位置后移n個字節 fileObject.seekg(n,ios::cur);//把文件的讀指針從fileObject末尾王回移n個字節 fileObject.seekg(n,ios::end);//定位到問價末尾 fileObject.seekg(0,ios::end);
?