c++文件操作-文本文件-读文件

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

//文本文件,读文件
void test01()
{
    //1.包含头文件

    //2.创建流对象
    ifstream ifs;

    //3.打开文件 并且判断是否打开成功

    ifs.open("text.txt", ios::in);
    if (!ifs.is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }

    //4.读数据

    ////第一种
    //char buf[99999] = { 0 };
    //while (ifs >> buf)
    //{
    //    cout << buf << endl;
    //}


    ////第二种
    //char buf[999999] = { 0 };
    //while (ifs.getline(buf, sizeof(buf)))
    //{
    //    cout << buf << endl;
    //}

    //第三种  推荐这种
    string buf;
    while (getline(ifs, buf))
    {
        cout << buf << endl;
    }


    ////第四种   这种效率慢
    //char c;
    //while ((c = ifs.get()) != EOF)
    //{
    //    cout << c;
    //}



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

int main()
{


    test01();

    system("pause");
    return 0;
}

 

posted @ 2021-09-05 23:12  梦之心  阅读(36)  评论(0编辑  收藏  举报