读文件
读文件步骤:
1.包含头文件
#include<fstream>
2.创建流对象
ifstream ifs;
3.打开文件并判断文件是否打开成功
ifs.open("文件路径",打开方式);
4.读数据
四种方式读取
5.关闭文件
ifs.close()
代码示例:
#include<iostream>
using namespace std;
#include<fstream>
#include<string>
//文本文件的读文件
void test01() {
//1、包含头文件
//2、创建流对象
ifstream ifs;
//3、打开文件并判断是否打开成功
ifs.open("test.txt", ios::in);
if (!ifs.is_open()) {
cout << "文件打开失败" << endl;
return;
}
//4、读数据(共4种方法)
第一种
//char buf[1024] = { 0 };
//while (ifs >> buf) {
// cout << buf << endl;
//}
//第二种
/*char buf[1024] = { 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)//get:每次只读一个字符 EOF:end of file :文件尾部的一个标志
{
cout << c;
}
//5、关闭文件
ifs.close();
}
int main() {
test01();
return 0;
}