文本文件--读文件

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;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值