#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;
}
12.1.2重学C++之【读文本文件】
猜你喜欢
转载自blog.csdn.net/HAIFEI666/article/details/114981181
今日推荐
周排行