读文件步骤:
- 包含头文件
#include<fstream>
- 创建流对象
ifstream ifs;
- 打开文件并判断文件是否打开成功
ifs.open ("文件打开路径”,打开方式)
- 读数据
四种方式读取 - 关闭文件
ifs.close();
#include<iostream>
#include<string>
#include<fstream>//包含头文件
using namespace std;
void t1()
{
//创建流对象
ifstream ifs;
//打开文件并判断文件是否打开成功
ifs.open("t1.txt", ios::in);
if (!ifs.is_open())//ifs.is_open()返回值为bool型,成功返回真,不成功返回假
{
cout << "文件打开失败" << endl;
return;
}
//读文件
//方法1:创建字符数组
char a[1024] = { 0 };//数组初始化为0
while (ifs >> a)//利用右移运算符把数据读到数组中
{
cout << a << endl;
}
//方法2:
//char a[1024] = { 0 };
//while (ifs.getline(a, sizeof(a)))//getline函数获取一行
//{
// cout << a << endl;
//}
//方法3:
//string a;
//while (getline(ifs, a))//此处的getline为全局函数
//{
// cout << a << endl;
//}
//方法4:
//char a;
//while ((a = ifs.get()) != EOF)//一个一个字符读入a里
// //EOF:end of file 文件尾
//{
// cout << a;
//}
//关闭文件
ifs.close();
}
int main()
{
t1();
system("pause");
return 0;
}
读文件可以用ifstream也可以用fstream(可读可写)
用is_open函数判断文件是否成功打开