C++连续读写多个文件
C++连续读写多个文件
当用同一个fstream对象file连续读写不同的文件时,读写下一个文件会和读写上一个文件的file的状态相关联。
示例和代码如下:
#include <fstream>#include <iostream>#include <cstdlib>using namespace std;int main () { fstream fin, fout; string str; //fstream::in|fstream::out fin.open( "1.txt", fstream::in ); fout.open( "2.1.txt", fstream::out ); while( fin >> str ) fout << str << endl; //status of fin cout << "end of file " << fin.eof() << endl; cout << "open file failed " << fin.fail() << endl; fin.close(); fout.close(); //将fin.eof的状态清除掉 fin.clear(); fin.open( "2.txt", fstream::in ); fout.open( "2.2.txt", fstream::out ); //status of fin cout << "end of file " << fin.eof() << endl; cout << "open file failed " << fin.fail() << endl; while ( fin >> str ) fout << str << endl; fin.close(); fout.close(); system( "pause" ); return 0;}
其中fin读取第一个文件到文件结尾,遇到eof,如果没有清理fin的状态,fin的遗留状态会影响读取下一个文件。
如果去掉fin.clear(),其中两处fin.eof()都会返回状态值1,否则,第一处fin.eof()返回1,第二处返回0。
open()函数原型:
void open (const char * filename, ios_base::openmode mode = ios_base::in | ios_base::out );
filename形式:filename="2.txt" || filename="D:\\file\\2.txt"
参考:http://www.cplusplus.com/reference/fstream/fstream/open/
http://blog.csdn.net/sutaizi/article/details/5068602