fstream对象重复使用需注意clear的调用,否则会出错

来源:互联网 发布:linux 查询 当前时间 编辑:程序博客网 时间:2024/05/17 23:03

 ifstream对象如果重复使用,须注意在使用之前先调用clear函数,否则会出错
表现为:
代码一:
====================================================
 ifstream fin("x.txt");
 if(fin.fail())
 {
  cout << " failed to open x.txt" << endl;
 }
 fin.close();
 fin.open("y.txt");
 if(fin.fail())
 {
  cout << " failed to open y.txt" << endl;
  //
  goto EXIT;
 }
 
 cout <<" succeed"<< endl;
EXIT:
 fin.close();
============================================
输出: failed to open y.txt
============================================
代码二:
============================================
 ifstream fin("y.txt");
 if(fin.fail())
 {
  cout << " failed to open y.txt" << endl;
 }
 fin.close();

// fin.clear(); //注意添加clear
 fin.open("x.txt");
 if(fin.fail())
 {
  cout << " failed to open x.txt" << endl;
  //
  goto EXIT;
 }
 
 cout <<" succeed"<< endl;
EXIT:
 fin.close();
=======================================
输出: failed to open y.txt
      failed to open x.txt
=======================================
代码二打开x.txt失败的
原因: 跟踪代码实现发现,在open成功后不会对 fstream中状态进行操作,而open失败的话会设置_MyState为failbit,并且在close操作时如果本身是空文件,也会设置state为failbit,这样造成一次失败之后的其他很多操作都是失败的,因为很多fstream操作会先判断state;

而clear函数是将fstream状态重置为goodbit

所以代码二在添加了clear代码后正常

 

TODO:

STL的文件流类挺复杂的——》《源码分析》TO SEE