C++ fstream 打开两次后读写失败

昨天写自己的课设的时候遇到的问题:

首先打开一个文件(这个文件名是不存在的 notexist.txt),打开失败。

再打开另一个文件(这个文件名存在 readme.txt),打开成功。

接着从redame.txt读取一个字符,发现读取失败了。

就是说在文件被打开一次后,第二次打开虽然成功打开,但是发生了错误。

 ifstream file ;

 char a ;
 file.open("notexist.txt");
 if ( !file.is_open() )
 {
  cout << " not exist" <<endl;
 }
 file.open("readme.txt");
 if ( file.is_open())
 {
  file >> a ;
 }
 cout << a << endl;




自己想了个很笨的方法

在打开文件前,先建一个测试流
    fstream test;
    test.open( bc.CommandContent );
    if ( !test.is_open() )
    {
     cout << "文件打开失败!请检查文件名是否正确" << endl;
     test.close();
     return ;
    }

 

通过查资料发现fstream存在状态:

当被打开第一次以后,状态处于错误状态。

 

fstream错误状态

fail() , eof() , bad();

failbit , eofbit ,badbit 。

正确状态

good(),

good = 非(fail 或 eof 或 bad)

= =离散太烂。。。见谅。。能看懂吧

在你第一次打开以后。failbit = 1 ;也就是说这个流的状态时错误的。

 

在使用close()以后,只是关闭文件,并没有销毁,也就是说,此时failbit任然是错误

 

对策 使用clear()函数:

fstream file ;
 char a[100];

 file.open("notexist.txt");
 if ( !file.is_open() )
 {
  cout << " not exist" <<endl;
  file.close(); 
 }
 
 cout << "isfail   " << file.fail() << endl;
 cout << "isbad   " << file.bad() << endl;
 cout << "iseof   " << file.eof() <<endl;
 cout << "isgood   "<< file.good() << endl;

 

 file.clear();
 //file.clear(file.eofbit);
 cout << "清除后" <<endl;

 cout << "isfail   " << file.fail() << endl;
 cout << "isbad   " << file.bad() << endl;
 cout << "iseof   " << file.eof() <<endl;
 cout << "isgood   "<< file.good() << endl;

 
 file.open("a.txt",ios::in);
 int i = 0 ;

 while( file.get(a[i]) )
 {
  cout << a[i];
 }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值