程序员社区

c++文件操作2之文本文件的读取操作

文本文件读取操作

读取文件操作:
1.包含头文件:#include< fstream >
2.创建流对象:ifstream ifs
3.打开文件,判断文件是否打开成功:ifs.open(“打开路径”,打开方式)
4.读取数据:有四种方式,下文用代码方式展现
5.关闭文件:ifs.close();

#include<iostream>
using namespace std;
#include<fstream>
#include<string>
void test()
{
	ifstream ifs;
	ifs.open("test.txt", ios::in);
	//判断文件是否打开成功函数:bool is_open()
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}
	//读数据
	//第一种:
	//文件变量名<<或>>:文件输入,输出流,类似cout
	char butf[1024] = { 0 };
	while (ifs >> butf)
	{
		cout << butf << endl;
	}

	//第二种:
	char  buf[1024] = { 0 };
	//用变量名.getline()的方式来读取文件中的一行数据
	//第一个参数是读出来的数据存放在某个字符串中
	//第二个参数是最多从文件读取多少字节的数据
	while (ifs.getline(buf, sizeof(buf))) 
	{
		cout << buf << endl;
	}

	//第三种:包含头文件string
	string 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;
}

赞(0) 打赏
未经允许不得转载:IDEA激活码 » c++文件操作2之文本文件的读取操作

相关推荐

  • 暂无文章

一个分享Java & Python知识的社区