c++文件操作

c++中对文件操作需要包含头文件<fstream>

文件类型分为两种:

1、文本文件:文件以文本的ASCII码存储在计算机中。

2、二进制文件:文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂。

操作文件的三大类:

1、ofstream 读文件

2、ifstream 读操作

3、fstream 读写操作

读文件:

#include <iostream>
using namespace std;
#include <fstream>

int main()
{

	ofstream ofs;
	ofs.open("text.txt",ios::out);
	ofs << "name:tom" << endl;
	ofs.close();
	system("pause");
	return 0;
}

总结:

文件操作必须包含头文件 fstream

读文件可以利用ofstream,或者发stream类

打开文件时候需要指定操作文件的路径,以及打开方式

利用<<可以向文件中写数据

操作完毕,要关闭文件

写文件:

 

#include <iostream>
using namespace std;
#include <fstream>
#include <string>
int main()
{
	ifstream ifs;
	ifs.open("text.txt",ios::in);

	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return 0;
	}

	//第一种方式
	char temp[1024] = { 0 };
	while (ifs >> temp)
	{
		cout << temp << endl;
	}

	//第二种方式
	char loop[1024] = { 0 };
	while (ifs.getline(loop, sizeof(loop)))
	{
		cout << loop << endl;
	}
	
	//第三种方式
	string buf;
	while (getline(ifs, buf))
	{
		cout << buf << endl;
	}
	ifs.close();
	system("pause");
	return 0;
}

总结:

读文件可以利用ifstream,或者fstream类

利用is_open函数可以判断文件是否打开成功

close关闭文件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值