#include <filesystem>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// 初始化文件路径
string path("test.txt");
// // 或者
// filesystem::path path("test.txt");
// 打开文件
ifstream input; // 也可使用ifstream input(path)在构造时打开文件
// 可以在打开文件前设置异常标志,一旦打开失败则自动抛出异常
input.exceptions(ios::failbit); // fail包含打开文件失败等可挽回的错误
input.open(path); // openmode默认为ios::in
input.exceptions(ios::goodbit); // 关闭自动抛出异常的功能
// // 如果打开文件前没有设置failbit异常标志,那么需要判断是否打开成功
// if (!input.is_open()) {
// throw runtime_error("failed to open file"); // 文件打开失败,程序终止
// }
// 从当前位置开始读取到换行符
string line;
getline(input, line);
cout << line << "\n";
// 从非空白符开始,到空白符结束
string word;
input >> word;
cout << word << "\n";
// 从非空白符开始,读取数字
int age;
input >> age;
cout << age << "\n";
// 尝试读取数字出错
try {
int number;
input.exceptions(ios::failbit); // 可以在读取数字之前设置异常标志,一旦出错则自动抛出异常
input >> number;
input.exceptions(ios::goodbit); // 关闭自动抛出异常的功能
// // 如果没有设置异常标志,则需要手动判断是否出现错误
// if (input.fail()) { // fail包含格式错误等可挽回的错误
// throw runtime_error("failed to read a number");
// }
cout << number << "\n";
} catch (exception& e) {
input.clear(); // 清除错误标志,否则此后无法正常读取内容
cerr << e.what() << "\n"; // cerr和cout近似,都是输出流,不过前者是专门用来输出错误信息的
}
// 读取剩下的所有内容
stringstream buffer;
buffer << input.rdbuf();
string all = buffer.str();
cout << all;
// // 如果只需要输出的话,可以直接
// cout << input.rdbuf();
// 读取到文件终止
cout << (input.eof() ? "end of file\n" : "still available\n"); // 输出still available
try {
input.exceptions(ios::eofbit); // 如果eof位被设置,则自动抛出异常
input.get(); // 此时input发现已经读取不到内容了,所以会设置failbit以及eofbit
} catch (exception &e) {
input.clear();
cerr << e.what() << "\n";
}
cout << (input.eof() ? "end of file\n" : "still available\n"); // 输出end of file
// // 文件重定位
// input.seekg(-10, ios::cur); // 回退10个字节
// input.seekg(ios::beg); // 从头开始读
// 最后一定要关闭文件
input.close();
}
C++ fstream读取文件的操作详细流程及解释
最新推荐文章于 2024-03-15 07:56:22 发布