打开文件时最常发生的是文件路径不正确问题导致文件打开失败或程序崩溃,因此需要处理文件打开错误异常。代码如下:
#include <iostream>
#include <windows.h>
#include <fstream>
using namespace std;
int main() {
SetConsoleOutputCP(CP_UTF8);
ifstream in;
try {
in.open("C:\\Users\\GuangshengLi\\Desktop\\exception\\a1.txt");
if (!in) {
throw "文件打开错误!请检查文件路径是否正确。";
}
} catch (const char *str) {
cout << str << endl;
}
string line;
getline(in, line);
cout << "line=" << line << endl;
return 0;
}
故意写错文件路径测试时程序输出: