C++ 读取文件的四种方式

   本文介绍C++ 读取文件的四种方式。

    第一种方式:

#include<iostream>
#include<fstream>
using namespace std;

int main()
{
    ifstream ifs;
    ifs.open("text.txt",ios::in);

    if (!ifs.is_open())
    {
        cout << "read fail." << endl;
        return -1;
    }
  
    char buf[1000] = { 0 };
    while (ifs >> buf)
    {
        cout << buf << endl;
    }

    getchar();
    return 0;
}

    第二种方式:

char buf[1000] = { 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;
}
发布了515 篇原创文章 · 获赞 135 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/liyazhen2011/article/details/103181754