fstream EOF意外引发异常 [英] fstream EOF unexpectedly throwing exception

查看:220
本文介绍了fstream EOF意外引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与上一个。我想打开并读取文件。我希望在无法打开文件时引发异常,但我不希望EOF引发异常。 fstream似乎可以让您独立控制是否在EOF,失败和其他不良事件上引发了异常,但是EOF似乎也倾向于映射到不良和/或失败异常。

My question is very similar to a previous one. I want to open and read a file. I want exceptions thrown if the file can't be opened, but I don't want exceptions thrown on EOF. fstreams seem to give you independent control over whether exceptions are thrown on EOF, on failures, and on other bad things, but it appears that EOF tends to also get mapped to the bad and/or fail exceptions.

这是我尝试做的一个精简示例。如果文件包含某个单词,函数f()应该返回true;如果文件中不包含某个单词,则该函数返回false;如果(例如)该文件不存在,则抛出异常。

Here's a stripped-down example of what I was trying to do. The function f() is supposed to return true if a file contains a certain word, false if it doesn't, and throw an exception if (say) the file doesn't exist.

#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,而是引发异常。

But it doesn't work, because basic fstream reading using operator>> is evidently one of the operations for which EOF sets the bad or the fail bit. If the file exists and does not contain "foo" the function does not return false as desired, but rather throws an exception.

推荐答案

如果目标是仅在打开文件时出现问题时才引发异常,为什么不写:

If the goal is to throw an exception only in case of a problem when opening the file, why not write:

bool f(const char *file)
{
    ifstream ifs;
    string word;

    ifs.open(file);
    if (ifs.fail())  // throw only when needed 
        throw std::exception("Cannot open file !");  // more accurate exception

    while (ifs >> word) {
        if (word == "foo") return true;
    }
    return false;
}

您当然可以设置:

ifs.exceptions(ifstream::badbit);

在开放前或开放后,抛出异常,以防万一在阅读过程中发生了某些非常糟糕的事情。

before or after the the open, to throw an exception in case something really bad would happen during the reading.

这篇关于fstream EOF意外引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆