读文件与写文件步骤相似,但是读取方式相对于比较多
读文件步骤如下:
- 包含头文件#include 
 - 创建流对象ifstream ifs;
 - 打开文件并判断文件是否打开成功ifs.open(“文件路径”,打开方式);
 - 读数据四种方式读取
 - 关闭文件ifs.close();
 
示例:
#include <fstream>#include <string>void test01(){ifstream ifs;ifs.open("test.txt", ios::in); // 打开方式为读文件if (!ifs.is_open()) // 判断文件是否打开成功{cout << "文件打开失败" << endl;return;}//第一种方式//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){cout << c;}ifs.close();}int main() {test01();system("pause");return 0;}
总结:
- 读文件可以利用 ifstream ,或者fstream类
 - 利用is_open函数可以判断文件是否打开成功
 - close 关闭文件
 
