【问题标题】:How to throw exception if file is empty in c++?如果文件在c ++中为空,如何抛出异常?
【发布时间】:2019-07-28 09:56:00
【问题描述】:

在下面的代码中,如果文件为空,我会尝试打印消息,然后抛出异常。考虑文件 Text.txt 是空的。

    ifstream inputFile;
try 
{
    inputFile.exceptions(ifstream::eofbit);
    inputFile.open("Text.txt");
    if (inputFile.is_open()) {
        cout << "file opened"<<endl;
    }
    if (inputFile.peek()== ifstream::traits_type::eof())
    {
        cout << "file opened but it is empty or invalid 
    content" << endl;
    }
}
catch (ifstream::failure &e)
{
    cout << "Some issue with input file: " << e.what()<<endl;
    _exit(1);
}

但它在进入 if 块之前抛出异常(if (inputFile.peek()== ifstream::traits_type::eof()))。我错过了什么?

【问题讨论】:

  • 异常错误说明了什么?请将错误添加到您的原始帖子中。

标签: c++ file exception


【解决方案1】:

当文件存在且为空时会发生此问题。 问题是您在以下行中启用了eof 的异常:inputFile.exceptions(ifstream::eofbit);

它打开文件,因为它是空的,它立即设置eof 标志,你得到一个异常。如果你注释掉这一行,它就可以正常工作。

无论如何,我会用更短的方式编写相同的代码:

    ifstream inputFile("Text.txt");
    if (inputFile) 
    {
        cout << "file opened" << endl;
        inputFile.peek();
        if (inputFile.eof())
        {
            cout << "file opened but it is empty or invalid content" << endl;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 2013-08-17
    相关资源
    最近更新 更多