2017-07-19 40 views
1

我的代碼集的std :: failbit當EOF到達並拋出異常 我怎麼能跳過EOF異常雖然在catch塊中處理了適當的eof後,我的代碼在達到eof時會提高basic_ios :: clear:

在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

[std :: getline當它碰到eof時可能會出現重複](https://stackoverflow.com/questions/11807804/stdgetline-throwing-when-it-hits-eof) –

+1

@CristianIonescu不,請不要讀我的直到最後問題我的擔心是我能否在catch block中處理? –

+0

@CristianIonescu沒有與我的問題有關的地方 –

回答

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; 
1

禁用failbit將會否則每次你會得到這個異常時,最好的辦法時(而函數getline())用來