c++ - 我的代码在达到 eof 时会引发 basic_ios::clear ,但在 catch block 中处理正确的 eof 之后?

标签 c++ file exception

我的代码在到达 eof 时设置 std::failbit 并抛出异常 我怎样才能跳过 eof 异常

在 catch block 中,我检查并跳过异常是否是由于 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;
}

最佳答案

经过私下讨论,我们设法解决了他的问题: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;

关于c++ - 我的代码在达到 eof 时会引发 basic_ios::clear ,但在 catch block 中处理正确的 eof 之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45191850/

相关文章:

c++ - Visual Studio 15 - 是否有更好的方法来查看/解释内存窗口中的内存?

python - 在 Python 和 C 之间共享文件流

parsing - 跳出深度递归函数调用

c++ - 不为私有(private)继承类创建的动态对象

c++ - 关于 C++ 头文件包含的基本问题?

将 ASCII 数字转换为其 ASCII 字符代码 - C(不打印!)

angular - Ionic 框架使用文件 API 创建文件

java - Spring Boot application.properties上传文件异常

java - 将 WebEnv 和 QueryKey 示例用于 EFetch 时出现 ADBException

c++ - MFC:嵌入式子对话框未显示在父对话框中