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()。