【问题标题】:My code raise basic_ios::clear when it reach eof though after proper eof handled in catch block?尽管在 catch 块中处理了正确的 eof 之后,我的代码在达到 eof 时会提高 basic_ios::clear 吗?
【发布时间】:2017-12-24 19:14:03
【问题描述】:

我的代码在到达 eof 并抛出异常时设置了 std::failbit 如何跳过 eof 异常

在 catch 块中,我检查并跳过异常是否是因为 eof 但它不好。

请建议我如何在下面的代码中跳过 eof 异常

std::ifstream in
std::string strRead;
in.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
try
{

while (getline( in,strRead))

{
         //reading the file
 }

 catch(std::ifstream::failure & exce)
{
         if(! in.eof())   // skip if exception because of eof but its not working?
        {
               cout<<exce.what()<<endl;
                return false;
        }


}
catch(...)
{

        cout("Unknow  exception ");
        return false;
}

【问题讨论】:

  • @CristianIonescu 不,请阅读我的直到结束的问题,我担心我是否可以在 catch 块中处理?
  • @CristianIonescu 没有与我的问题相关的地方
  • 请提供MVCE
  • @CristianIonescu 你没有分享的链接在哪里谈到在我的代码执行的 catch 块中处理 eof 异常,这就是我所有的问题。我请求你阅读我所有的问题并比较你分享的那个

标签: c++ file exception-handling


【解决方案1】:

经过私下讨论,我们设法找到了解决他问题的方法:getline(in, strRead) 会在达到 eof 时将故障位设置为 1(正常行为),他不希望这种情况发生。我们同意使用其他读取文件内容的方法:

std::ifstream in(*filename*); // replace *filename* with actual file name.
// Check if file opened successfully.
if(!in.is_open()) {
       std::cout<<"could not open file"<<std::endl;
       return false;
}

in.seekg(0, std::ios::end);
std::string strRead;

// Allocate space for file content.
try {
    strRead.reserve(static_cast<unsigned>(in.tellg()));
} catch( const std::length_error &le) {
    std::cout<<"could not reserve space for file"<<le.what()<<std::endl;
    return false;
} catch(const std::bad_alloc &bae) {
    std::cout<<"bad alloc occurred for file content"<<bae.what()<<std::endl;
    return false;
} catch(...) {
    std::cout<<"other exception occurred while reserving space for file content"<<std::endl;
    return false;
}

in.seekg(0, std::ios::beg);
// Put the content in strRead.
strRead.assign(std::istreambuf_iterator<char>(in),
        std::istreambuf_iterator<char>());
// Check for errors during reading.
if(in.bad()) {
    std::cout<<"error while reading file"<<std::endl;
    return false;
}

return true;

【讨论】:

    【解决方案2】:

    禁用故障位将是最好的方法,否则每次在使用(而 getline() 时)时都会收到此异常

    【讨论】:

      猜你喜欢
      • 2017-06-27
      • 2017-10-21
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多