#include<stdlib.h>
#include<iostream>
#include<string>
#include<fstream> // 包含头文件
using namespace std;



/*
    5.1.2 读文本文件
        读文件可以利用 ifstream ,或者fstream类
*/



void test1(){
    // 1 包含头文件<fstream>


    // 2 创建流对象
    ifstream ifs;


    // 3 打开文件并判断是否打开成功
    ifs.open("test.txt", ios::in);
    if(!ifs.is_open()){
        cout << "文件打开失败" << endl;
        return;
    }


    // 4 读内容

    /*
    // 方法1
    char buf[1024] = {0};
    while(ifs >> buf){
        cout << buf << endl;
    }
    */

    /*
    // 方法2
    char buf[1024] = {0};
    while(ifs.getline(buf, sizeof(buf))){
        cout << buf << endl;
    }
    */

    // 方法3(推荐)
    string buf;
    while(getline(ifs, buf)){
        cout << buf << endl;
    }

    /*
    // 方法4(不推荐)
    char c;
    while( (c=ifs.get()) != EOF ){ // EOF:end of file
        cout << c;
    }
    */


    // 5 关闭文件
    ifs.close();
}



int main()
{
    test1();

    system("pause");
    return 0;
}

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐