C++中的文件流有三種:ifstream - 由istream派生而來,提供讀文件的功能
ofstream - 由ostream派生而來,提供寫文件的功能
fstream - 由iostream派生而來,提供讀寫同一個文件的功能
先說ifstream文件流,對文件進行讀操作。
從文件中讀取內容有多種方式. 一行一行地讀:使用string結構;
1 ifstream fin(filename.c_str(), ifstream::in | ifstream::binary);
2 if (fin == NULL)
3 {
4 cerr << "error in open the JPG FILE.." << endl;
5 exit(-1);
6 }
7 string temp;
8 while (getline(fin,temp))
9 {
10 cout << temp << endl;
11 }
使用char []結構;
1 #define MAX_STRLEN 1024
2
3 ifstream fin(filename.c_str(), ifstream::in | ifstream::binary);
4 if (fin == NULL)
5 {
6 cerr << "error in open the JPG FILE.." << endl;
7 exit(-1);
8 }
9 char temp[MAX_STRLEN];
10 const int LINE_LENGTH = 100;
11 while (fin.getline(temp,LINE_LENGTH))
12 {
13 cout << temp << endl;
14 }
一個單詞一個單詞的讀入文件:
1 ifstream fin(filepath.c_str(), ifstream::in | ifstream::binary);
2 string temp;
3 while( fin >> temp )
4 {
5 cout << temp << endl;
6 }
文件流在打開文件的時候需要說明打開模式:in - 打開文件做讀操作;out - 打開文件做寫操作;app - 每次寫之前找到文件尾;ate - 打開文件后立即將文件定位在文件尾;trunc - 打開文件時清空已存在的文件流。其中out、trunc 和 app模式只能夠與ifstream或fstream對象關聯,所有的文件流對象都可以 ate 和 binary。
規范的文件流操作,在生成對象的時候要檢驗是否成功,當不需要對文件進行操作時,要關閉文件fin.close(),並清空文件流狀態fin.clear()。