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重置。
- fstream打开失败后重新打开新文件一个问题
- C++ fstream 打开两次后读写失败
- fstream文件打开模式
- 打开文件函数fstream
- fstream打开文件模式
- fstream打开文件模式
- fstream: 打开文件方式
- fstream 打开文件失败,读取文件内容为空
- 用fstream打开含中文路径文件时失败的问题。
- 用fstream打开含中文路径文件时失败的问题。
- fstream打开中文名的文件时失败的处理方法
- fstream打开中文路径问题
- 解决fstream不能打开带有中文路径文件的问题
- VS2005 FSTREAM 不能打开中文路径名文件的问题!
- 关于无法打开包含文件:“fstream.h” 的问题
- jsp页面怎样实现重新打开一个新的页面
- win7 chm后缀文件打开失败问题.
- fstream对象重复使用时注意clear()的调用,否则会造成打开第二个文件失败
- HDU 4289 Control
- 反射机制(-)
- SQL 查询时join的顺序问题
- 大数相乘(浮点数)poj1001
- 南阳理工102 次方求模
- fstream打开失败后重新打开新文件一个问题
- 从今开始
- wp7中关于ListPicker的ItemSource的一个疑问
- CSS content内容生成技术以及应用
- Linux sendmail启动慢的问题 - 修正方法
- Mac OS X系统偏好设置无法保存问题解决
- HDU 4279 Food
- UDP socket(二)
- 二叉树