c++文件操作2之文本文件的读取操作
文本文件读取操作
读取文件操作:
1.包含头文件:#include
2.创建流对象:ifstream ifs
3.打开文件,判断文件是否打开成功:ifs.open(“打开路径”,打开方式)
4.读取数据:有四种方式,下文用代码方式展现
5.关闭文件:ifs.close();
#includeusing namespace std;#include#includevoid test(){ifstream ifs;ifs.open("test.txt", ios::in);//判断文件是否打开成功函数:bool is_open()if (!ifs.is_open()){cout << "文件打开失败" << endl;return;}//读数据//第一种://文件变量名<>:文件输入,输出流,类似coutchar butf[1024] = { 0 };while (ifs >> butf){cout << butf << endl;}//第二种:char buf[1024] = { 0 };//用变量名.getline()的方式来读取文件中的一行数据//第一个参数是读出来的数据存放在某个字符串中//第二个参数是最多从文件读取多少字节的数据while (ifs.getline(buf, sizeof(buf))) {cout << buf << endl;}//第三种:包含头文件stringstring buf1;//getline(输入流,字符串) while(getline(ifs,buf1)){cout << buf1 << endl;}//第四种char c;//ifs.get()每次读取一个字符//EOF文件结束标识符while ((c = ifs.get() )!= EOF){cout << c ;}ifs.close();}int main(){test();return 0;}