fstream打开失败后重新打开新文件一个问题

请看这则代码,看看你能不能发现其中的错误:

	ifstream fileStream(fileName.c_str());
	while (fileStream.fail())
	{
		string tmpFileName;
		cout<<"打开文件失败!请输入文件名:"<<endl;
		cin>>tmpFileName;
		fileStream.open(tmpFileName.c_str(),ios::in);
	}

在测试过程中发现,即使是全英文的绝对路径,这里也是死循环。后来在CSDN看到 http://topic.csdn.net/u/20101014/09/8AF9EB40-3D8F-4931-BA41-CACD891C35D1.html

这个帖子,才知道错在哪里。

先贴上正确的代码:

	ifstream fileStream(fileName.c_str());
	while (fileStream.fail())
	{
		string tmpFileName;
		cout<<"打开文件失败!请输入文件名:"<<endl;
		cin>>tmpFileName;
		//
		fileStream.clear();
		//
		fileStream.open(tmpFileName.c_str(),ios::in);
	}

其中的 fileStream.clear();就是问题的关键所在。

让我们看看 fstream::open的参考:http://www.cplusplus.com/reference/iostream/fstream/open/

原文:

Open file
Opens a file whose name is  filename , associating its content with the stream object to perform input/output operations on it. The operations allowed and some operating details depend on parameter  mode .

The function effectively calls  rdbuf ()-> open (filename,mode).

If the object already has a file associated (open), the function fails.

On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.

后面红色这句是说,打开失败的话,失败flag会被置位,并根据设置的值可能会抛出异常,

再看看fstream::clear

void clear ( iostate state = goodbit );
Set error state flags
Sets a new value for the error control state.

All the bits in the  control state  are replaced by the new ones; The value existing before the call has no effect.

If the function is called with  goodbit  as argument (which is the default value) all error flags are cleared.

The current state can be obtained with member function  rdstate .

这里是给 错误状态 重新设定一个新的置,并且默认是goodbit。也就是说,一开始fstream中的errorState应该是goodbit,如果打开失败了,就设置为其他值,fail()中可以根据这个值检测打开是否成功。但是如果打开成功了,并不会设置这个值为新的值,必须手工调用clear重置。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值