Jer*_*iah 8 c++ file-io exception getline eof
是否可以getline()在没有设置的情况下读取有效文件failbit?我想使用,failbit以便在输入文件不可读时生成异常.
以下代码始终basic_ios::clear作为最后一行输出- 即使指定了有效输入.
test.cc:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
ifstream inf;
string line;
inf.exceptions(ifstream::failbit);
try {
inf.open(argv[1]);
while(getline(inf,line))
cout << line << endl;
inf.close();
} catch(ifstream::failure e) {
cout << e.what() << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
input.txt中:
the first line
the second line
the last line
Run Code Online (Sandbox Code Playgroud)
结果:
$ ./a.out input.txt
the first line
the second line
the last line
basic_ios::clear
Run Code Online (Sandbox Code Playgroud)
你不能.标准说getline:
如果函数没有提取任何字符,则调用
is.setstate(ios_base::failbit)可能抛出的字符ios_base::failure(27.5.5.4).
如果你的文件以空行结束,即最后一个字符是'\n',则最后一次调用getline不会读取任何字符并失败.实际上,如果不设置failbit,你是如何想要循环终止的呢?这种情况while永远是真实的,它将永远存在.
我认为你误解了failbit的含义.它并不意味着文件无法读取.它被用作最后一次操作成功的标志.为了表示低级故障,使用了badbit,但它几乎没有用于标准文件流.failbit和eofbit通常不应被解释为例外情况.另一方面,badbit应该,并且我认为fstream :: open应该设置badbit而不是failbit.
无论如何,上面的代码应该写成:
try {
ifstream inf(argv[1]);
if(!inf) throw SomeError("Cannot open file", argv[1]);
string line;
while(getline(inf,line))
cout << line << endl;
inf.close();
} catch(const std::exception& e) {
cout << e.what() << endl;
}
Run Code Online (Sandbox Code Playgroud)