我的代码设置std :: failbit到达eof并抛出异常 我怎么能跳过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;
}
答案 0 :(得分:1)
当使用(使用getline())时,每次获得此异常时,禁用failbit将是最好的方法
答案 1 :(得分:1)
在私下讨论之后,我们设法找到了解决问题的方法:getline(in, strRead)
会在达到eof时将failbit设置为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;