C++的文件操作详解

目录

1.文本文件

1.写文件  

2.读文件 

 2.二进制文件

1.写文件

2.读文件


1.文本文件

 

1.写文件  

 

#include<bits/stdc++.h>
#include<fstream>
using namespace std;

int main()
{
	ofstream ofs;
	ofs.open("text.txt",ios::out);
	
	ofs << "abc" << endl;
	ofs << 123 << endl;
	
	ofs.close();
	
	return 0;
}

打开文件所在的文件夹即可发现一个新文件 

 

2.读文件 

#include<bits/stdc++.h>
#include<fstream>
using namespace std;

int main()
{
	ifstream ifs;
	ifs.open("test.txt",ios::in);
	
	//如果成功打开了返回真,否则返回假
	ifs.is_open();
	if(!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return 0;
	}
	
	//读数据
	//第一种
	// 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;
	//getline里第一个空是输入流对象,也就是ifs
	//第二个是准备好的字符串,这里为buf
	// while(getline(ifs,buf))
	// {
	// cout << buf << endl;
	// }
	
	//第四种,效率低,不太推荐
	char c;
	//没有读到尾就一直读,EOF代表文件尾end of file
	while((c = ifs.get()) != EOF)
	{
		cout << c;
	}
	
	ifs.close();
	
	return 0;
}

 

 

 2.二进制文件

1.写文件

#include<bits/stdc++.h>
#include<fstream>
using namespace std;

class person
{
public:
	//写入文件时最好用字符数组而不是c++里的字符串
	char name[10];
	int id;
};
int main()
{
	ofstream ofs("person.txt",ios::out | ios::binary);
	
	//先创建ofs再这样写也行
	//ofs.open("person.txt",ios::out | ios::binary);
	
	person p = {"xiaoming",1};
	
	ofs.write((const char *)&p,sizeof(person));
	
	ofs.close();
	
	return 0;
}

打开文件所在文件夹 

 

以二进制的方式写入,所以会有乱码存在 

 

 

2.读文件

 

#include<bits/stdc++.h>
#include<fstream>
using namespace std;

class person
{
public:
	//写入文件时最好用字符数组而不是c++里的字符串
	char name[10];
	int id;
};

int main()
{
	ifstream ifs;
	ifs.open("person.txt",ios::in | ios::binary);
	if(!ifs.is_open())
	{
		cout << "打开失败" << endl;
	}
	
	person p;
	ifs.read((char *)&p, sizeof(person));
	
	cout << p.name << ' ' << p.id << endl;
	
	ifs.close();
	
	return 0;
}

 

  • 14
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柏箱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值