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

来源:互联网 发布:支付宝mac版下载 编辑:程序博客网 时间:2024/06/02 20:34

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

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重置。


原创粉丝点击