我正在编写一个修改文本文件的小应用程序。它首先创建文件的副本,以防出问题。
下面的函数在同一个目录中创建此副本。它以文件名作为参数,如果成功创建副本,则返回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的捕获时,它运行得很好。
为什么是这种情况?
发布于 2022-09-22 14:32:11
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://stackoverflow.com/questions/73816371
复制相似问题