我的问题与 a previous one 非常相似。我想打开并读取一个文件。我希望在文件无法打开时抛出异常,但我不希望在 EOF 上抛出异常。 fstreams 似乎可以让您独立控制是否在 EOF、失败和其他不良情况下引发异常,但 EOF 似乎也倾向于映射到不良和/或失败异常。
这是我想要做的事情的一个精简示例。如果文件包含某个单词,函数 f() 应该返回 true,如果不包含某个单词,则返回 false,如果(比如说)文件不存在,则函数 f() 应该返回异常。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
bool f(const char *file)
{
ifstream ifs;
string word;
ifs.exceptions(ifstream::failbit | ifstream::badbit);
ifs.open(file);
while(ifs >> word) {
if(word == "foo") return true;
}
return false;
}
int main(int argc, char **argv)
{
try {
bool r = f(argv[1]);
cout << "f returned " << r << endl;
} catch(...) {
cerr << "exception" << endl;
}
}
但它不起作用,因为使用运算符 >> 进行基本的 fstream 读取显然是 EOF 设置错误或失败位的操作之一。如果文件存在并且不包含“foo”,则该函数不会根据需要返回 false,而是抛出异常。
最佳答案
当文件到达末尾时尝试提取时,也会设置 std::ios_base::failbit
标志,这是流的 bool 运算符的行为允许的。您应该在 f()
中设置一个额外的 try-catch block ,并在与文件结束条件不符时重新抛出异常:
std::ifstream ifs;
std::string word;
ifs.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
ifs.open(file);
while (ifs >> word) {
if (word == "foo") return true;
}
}
catch (std::ios_base::failure&) {
if (!ifs.eof())
throw;
}
return false;
关于c++ - fstream EOF 意外抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25213540/