C++文件操作

写文件:

cpp 复制代码
#include<iostream>
#include<fstream>
using namespace std;
void test01()
{
	ofstream ofs;
	ofs.open("test.txt",ios::out);
	ofs<<"姓名:张三"<<endl;
	ofs<<"性别:男"<<endl;
	ofs<<"年龄:18"<<endl; 
	ofs.close();
}
int main()
{
	test01();
}

读文件:

cpp 复制代码
#include<iostream>
#include<fstream>
using namespace std;
void test01()
{
	ifstream ifs;
	ifs.open("test.txt",ios::in);
	if(!ifs.is_open())
	{
		cout<<"文件打开失败"<<endl;
		return;
	}
	//第一种方式:
	char buf[1024]={0};
	while(ifs>>buf)
	{
		cout<<buf<<endl;
	}
	//第二种方式:
	char buf1[1024]={0};
	while(ifs.getline(buf1,sizeof(buf1)))
	{
		cout<<buf1<<endl;
	}
	//第三种方式:
	string buf2;
	while(getline(ifs,buf2))
	{
		cout<<buf2<<endl;
	}
	//第四种方式:
	char c;
	while((c=ifs.get())!=EOF)
	{
		cout<<c;
	}
	ifs.close();
}
int main()
{ 
	test01();
}

推荐使用第三种方式,代码量少,好记。

二进制写文件:

cpp 复制代码
#include<iostream>
#include<fstream>
using namespace std;
class Person
{
public:
	char m_Name[64];
	int m_Age;
};
void test01()
{
	ofstream ofs("person.txt",ios::out|ios::binary);
	Person p={"张三",18};
	ofs.write((const char*)&p,sizeof(Person));
	ofs.close();
}
int main()
{ 
	test01();
}

二进制读文件:

cpp 复制代码
#include<iostream>
#include<fstream>
using namespace std;
class Person
{
public:
	char m_Name[64];
	int m_Age;
};
void test01()
{
	ifstream ifs("person.txt",ios::in|ios::binary);
	if(!ifs.is_open())
	{
		cout<<"文件打开失败"<<endl;
		return;
	}
	Person p;
	ifs.read((char*)&p,sizeof(Person));
	cout<<"姓名:"<<p.m_Name<<" 年龄:"<<p.m_Age<<endl;
	ifs.close();
}
int main()
{ 
	test01();
}
相关推荐
SilentSamsara1 分钟前
HTTP 客户端实战:httpx/重试/限速/连接池/中间件设计
开发语言·网络·python·http·青少年编程·中间件·httpx
Hall_IC1 分钟前
LSM6DS3TR-C现货询价丨粤科源兴ST代理商,专业FAE技术支持
c++
进击的荆棘3 分钟前
优选算法——队列+宽搜
数据结构·c++·算法·leetcode·bfs·队列
Irissgwe4 分钟前
STL简介
c++·stl
江屿风7 分钟前
C++OJ题经验总结(竞赛)4
开发语言·c++·笔记·算法·dp·双指针
Deep-w7 分钟前
【MATLAB】微电网四DG逆变器下垂策略与分布式MPC协同控制仿真分析
开发语言·分布式·算法·matlab
酉鬼女又兒7 分钟前
零基础入门计算机网络:定义、分类与核心性能指标
开发语言·计算机网络·考研·青少年编程·职场和发展·php
码上有光7 分钟前
c++: 继承(下)
android·java·c++·多继承·菱形继承·虚继承
AI玫瑰助手12 分钟前
Python函数:可变参数(星号args与双星号kwargs)详解
android·开发语言·python
进击的荆棘13 分钟前
优选算法——栈
数据结构·c++·算法·leetcode·