C++文件操作

文件:
文本文件和二进制文件。

文件操作:
1.包含头文件#include。
2.创建流对象。读文件流对象 ifstream ifs; 写文件流对象 ofstream ofs;
3.打开文件。读文件:ifs.open("文件名或文件路径”,打开方式);
写文件:ofs.open("文件名或文件路径”,打开方式);
打开方式:(多种方式并用用“|”运算符连接)
ios::in 以读文件形式打开文件
ios::out 以写文件形式打开文件
ios::ate 初始位置为文件尾
ios::app 以追加方式写文件
ios::trunc如果文件存在,先删除后创建
ios::binary 二进制方式
4.若为打开文件,需判断是否打开文件成功。
5.读数据/写数据。
写文本文件:ofs<<“”数据”;
读文本文件:typedef a;while(getline(ifs,a){cou<<a;}
写二进制文件:ofs.write((const char*)&p1,sizeof(person));
读二进制文件:ifs.read((char*)&p,sizeof(person));
6.关闭文件。ifs.close( );/ofs.close();

写文本文件例子

#include <iostream>
#include<fstream>
using namespace std;
int main()
{
	ofstream ofs;
	ofs.open("file.txt", ios::out);
	ofs << "姓名:HC" << endl;
	ofs << "录取情况:拟录取" << endl;
	ofs.close();
	return 0;
}

在这里插入图片描述

读文本文件例子

#include <iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
	ifstream ifs;
	ifs.open("文本文件1.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "文件打开失败";
		return 0;
	}
	//第一种方法:
	//char a[1024] = { 0 };
	//while (ifs >> a)//一行一行读,读到0停止,继续读下一行
	//{
	//	cout << a<<endl;
	//}
	//第二种方法:
	//char a[1024] = { 0 };
	//while (ifs.getline(a, sizeof(a)))
	//{
	//	cout << a << endl;
	//}
	//第三种方法:
	string a;
	while (getline(ifs, a))
	{
		cout << a << endl;
	}
	ifs.close();
	return 0;
}

在这里插入图片描述

写二进制文件例子

#include <iostream>
#include<fstream>
using namespace std;
class person
{
public:
	char name[20];
	int number;
};
int main()
{
	ofstream ofs;
	ofs.open("file.txt", ios::binary | ios::out);
	person p1{ "张三",110 };
	ofs.write((const char*)&p1, sizeof(person));
	ofs.close();
	return 0;
}

在这里插入图片描述
读二进制文件例子

#include <iostream>
#include<fstream>
using namespace std;
class person
{
public:
	char name[20];
	int number;
};
int main()
{
	ifstream ifs;
	ifs.open("file.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return 0;
	}
	person p;
	ifs.read((char*)&p, sizeof(person));
	cout << "姓名:" << p.name <<endl<< "学号:" << p.number;
	ifs.close();
}

在这里插入图片描述
将数组写入文件并读取实例

#include <iostream>
#include<fstream>
using namespace std;
int main()
{
	ofstream ofs;
	ofs.open("数组.txt", ios::out);
	ofs << 0 <<" "<< 1 <<" "<< 1 << endl;
	ofs << 1 <<" "<< 1 <<" "<< 1 << endl;
	ofs << 0 <<" "<<0 << " "<< 1 << endl;
	ofs.close();
	ifstream ifs;
	ifs.open("数组.txt", ios::in);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return 0;
	}
	int a[3][3];
	while (!ifs.eof()) {
		for (int i = 0; i < 3; i++)
			for (int j = 0; j < 3; j++)
				ifs >> a[i][j];
	}
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 3; j++)
			cout << a[i][j] << " ";
		cout << endl;
	}
	ifs.close();
}

在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值