C++ fstream读取文件的操作详细流程及解释

#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();
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值