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();
}
相关推荐
2501_9445215919 小时前
Ramda 跨端三方库仓颉适配全流程
开发语言·javascript·flutter·php
行思理19 小时前
go语言学习难度及适合学习的人群
开发语言·学习·golang
青瓦梦滋19 小时前
WebSocket协议
linux·服务器·网络·c++·websocket·网络协议·http
wangchunyu11421 小时前
JAVA CompletableFuture异步编程实战
java·开发语言·python
程序 代码狂人1 天前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
meiying88381 天前
快递单号批量查询Python脚本:从手动到自动化的完整实现
开发语言·python·自动化
@大迁世界1 天前
告别 Go,拥抱 Rust
开发语言·golang·rust
SEO_juper1 天前
Node.js 重定向链检测工具:301 跳了几跳、有没有成环,一次看清
xml·开发语言·python·node.js·json·bash
学逆向的1 天前
C 指针常量与常量指针
c语言·开发语言·网络安全
低调滴开发1 天前
3 行代码写崩一个函数?切片才是 Rust 字符串处理的正确姿势
开发语言·后端·rust