我正在撰寫一個修改文本檔案的小應用程式。它首先創建檔案的副本以防出現問題。
以下函式在同一目錄中創建此副本。它將檔案名作為引數,如果副本創建成功則回傳 true,如果創建失敗則回傳 false。
#include <iostream>
#include <filesystem>
#include <fstream>
#include <string>
using std::ifstream;
using std::ofstream;
using std::string;
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
bool backupFile(string FileName) {
cout << "Creating backup for " << FileName << "..." << endl;
try { // for debugging purposes
string NewName = "bkp_" FileName;
string CurLine;
ifstream FileCopy(FileName);
ofstream FileBackup(NewName);
if (FileCopy.fail()) { // Could specify how file copy failed?
cerr << "Error opening file " << FileName << ".";
return false;
}
while (getline(FileCopy, CurLine)) { // Copy lines to new file
//cout << "Copying " << CurLine << "\" to " << NewName << "." << endl;
FileBackup << CurLine << "\n";
}
cout << "File successfully backed up to " << NewName << endl;
return true;
}
catch (const ifstream::failure& iE) {
cerr << "Exception thrown opening original file: " << iE.what() << endl;
return false;
}
catch (const ofstream::failure& oE) {
cerr << "Exception thrown outputting copy: " << oE.what() << endl;
}
catch (...) {
cerr << "Unknown exception thrown copying file." << endl;
return false;
}
}
我使用了一些 catch 陳述句來指示輸入 (ifstream::failure)、輸出 (ofstream::failure) 是否存在問題,或者兩者都沒有。
但是,在編譯程序中,會出現以下錯誤:
error C2312: 'const std::ios_base::failure &': is caught by 'const std::ios_base::failure &' on line 42
對我來說,該錯誤意味著 ifstream::failure 和 ofstream::failure 都被 ifstream::failure 捕獲,這看起來很奇怪。當我洗掉 ofstream::failure 的捕獲時,它運行良好。
為什么會這樣?
uj5u.com熱心網友回復:
ifstream::failure并且ofstream::failure都是在std::ios_base基類中定義的相同型別std::ios_base::failure,您不能在兩個單獨的catch子句中捕獲相同的型別。
請注意,您的兩個流實際上都不會引發任何例外,默認情況下std::fstream不會引發任何例外。您必須通過呼叫打開例外exceptions:
FileCopy.exceptions(f.failbit);
FileBackup.exceptions(f.failbit);
std::ios_base::failure當流進入失敗狀態時,上面將導致拋出一個。由于您已經在檢查,FileCopy.fail()您可以擴展該檢查以涵蓋其他失敗情況(例如檢查FileCopy期間不會失敗getline并且FileBackup也不會失敗),而不是啟用例外。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513368.html
