本文介绍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;
}