C++ 文件操作

文本文件的操作:文件以文本的ASCLL码的形式存储在计算机

包含头文件流<fstream>

写:ofstream

读:ifsream

可读可写:fstream

写文件操作步骤

包含头文件--->创建流对象----->打开文件---->写入数据----->关闭文件

文件打开的方式:

写文件示例!

cpp 复制代码
#include<iostream>
#include<fstream>
using namespace std;

void test()
{
//创建对象流
	ofstream ofs;
	//指定打开方式
	ofs.open("test.txt", ios::out);
	//写入内容
	ofs << "123123一二三123!" << endl;
	ofs << "123123一二三123!" << endl;
	ofs << "123123一二三123!" << endl;
	ofs << "123123一二三123!" << endl;
	//关闭文件
	ofs.close();
}

int main()
{

	test();
	
	system("pause");
	return 0;
}

读文件操作:5步

cpp 复制代码
void test()
{
//创建对象流
	ifstream ifs;
	//指定打开方式
	ifs.open("test.txt", ios::in);
	//打开文件,判断是否打开成功
	if (!ifs.is_open())
	{
		cout << "open erro" << endl;
		return;
	}
	//读数据
	char buffer[1024];
	while (ifs >> buffer)
	{
		cout << buffer << endl;
	}

	/*
	成员函数getline 获取一行
	char buf[1024]={0};
	将读到的数据放入buf
	while(ifs.getline(buf,sizeof(buf))
	{
	cout<<buf<<endl;
	}
	*/


	/*
	string buf;
	while(getline(ifs,buf))
	*/
	//关闭文件
	ifs.close();
}

int main()
{

	test();
	
	system("pause");
	return 0;
}

二进制文件的读写!

打开方式需要指定: iso::binary

利用流对象调用成员函数write

ostream& write(const chatr*buffer,int len);

字符指针 buffer指向内存中的一段储存空间,len为读取的字节数

cpp 复制代码
class Person
{
public:
	char name[64];
	int m_age;
};

void test()
{
//创建对象流
	ofstream ofs;
	ofs.open("person,txt",ios::out|ios::binary);
	//ofstream ofs("person,txt",ios::out|ios::binary);
	//写文件
	Person p = { "yyyyy",20 };
	ofs.write((const char*)&p, sizeof(Person));
}

读取二进制文件

read函数

cpp 复制代码
void test02()
{
	ifstream ifs;
	ifs.open("person,txt", ios::out | ios::binary);
		if (!ifs.is_open())
		{
			cout << "open erro" << endl;
			return;
		}
		Person p;
		ifs.read((char*)&p, sizeof(Person));
		cout << p.m_age << endl;
		cout << p.name << endl;
}
相关推荐
weixin199701080165 分钟前
《淘宝TOP API:落地方案、接口边界与业务踩坑 —— 聚石塔内外价差 10 倍的真相》(附 Python 源码)
开发语言·python
前端 贾公子7 分钟前
LangGraph == 图的状态(State)管理 (上)
java·开发语言·数据库
汉克老师30 分钟前
CSP-S 2026 初赛试题解析(第一部分:选择题(8-15))精讲
c++·csp-s·小学生·学c++编程
_wyt00136 分钟前
洛谷 P10112 [GESP202312 八级] 奖品分配 题解
c++·数学·gesp·八级
xuxigifxfh1 小时前
牛客:HJ170 01序列
java·开发语言·算法·华为机考
朝朝辞暮i1 小时前
C++ 第 33 课:事件循环——spin() 到底在干什么
开发语言·c++·算法
野生技术架构师1 小时前
牛客网互联网大厂 Java 高频面试题整理(持续更新)
java·开发语言
殷色玫瑰1 小时前
AVL树:从平衡因子到四种旋转的完整实现
c语言·数据结构·c++·算法·visualstudio
小师兄吃牛肉2 小时前
Java语法 | 多重循环
java·开发语言·python
进化中的刀盾兽2 小时前
从零实现 C++ AI 大模型接入 SDK(九):LLMManager 统一模型管理与请求路由
c++