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();
}
相关推荐
风逸hhh17 分钟前
python打卡day25@浙大疏锦行
开发语言·python
刚入门的大一新生21 分钟前
C++初阶-string类的模拟实现与改进
开发语言·c++
小冯的编程学习之路1 小时前
【软件测试】:推荐一些接口与自动化测试学习练习网站(API测试与自动化学习全攻略)
c++·selenium·测试工具·jmeter·自动化·测试用例·postman
chxii2 小时前
5java集合框架
java·开发语言
老衲有点帅2 小时前
C#多线程Thread
开发语言·c#
C++ 老炮儿的技术栈2 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
IsPrisoner2 小时前
Go语言安装proto并且使用gRPC服务(2025最新WINDOWS系统)
开发语言·后端·golang
猪八戒1.02 小时前
C++ 回调函数和Lambda表达式
c++
Python私教2 小时前
征服Rust:从零到独立开发的实战进阶
服务器·开发语言·rust