1.步骤
- 包含头文件 #include<fstream>
- 创建流对象 ifstream ifs;
- 打开文件并判断文件是否打开成功 ifs.open("文件路径“,打开方式)
- 读数据 四种方式
- 关闭文件 ifs.close();
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
//文本文件 读文件
void test1()
{
ifstream ifs;
//ofs.open("test.txt", ios::out);//创建text文件到该项目cpp同级文件夹下
ifs.open("C:\\Users\\小明桑\\Desktop\\test.txt", ios::in); //路径中的'\'在open()语句中需要变成'\\'
if (!ifs.is_open())
{
cout << "文件打开失败" << endl;
return;
}
//读数据
//第一种
//char buff[1024] = { 0 };
//while (ifs >> buff)
//{
// cout << buff << endl;
//}
//第二种
/*char buff[1024] = { 0 };
while (ifs.getline(buff, sizeof(buff)))
{
cout << buff << endl;
}*/
//第三种
//string buff;
//while (getline(ifs, buff))
//{
// cout << buff << endl;
//}
//第四种 不推荐
char c;
while ((c = ifs.get()) != EOF) // EOF: end of file
{
cout << c;
}
ifs.close();
}
int main()
{
test1();
system("pause");
return 0;
}