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();
}
相关推荐
艾莉丝努力练剑13 小时前
【Linux网络】Linux 网络编程入门:TCP Socket 编程(下)
linux·运维·服务器·网络·c++·tcp/ip
宵时待雨13 小时前
linux笔记归纳4:进程概念
linux·运维·服务器·c++·笔记
凯瑟琳.奥古斯特13 小时前
力扣2760 C++滑动窗口解法
数据结构·c++·算法·leetcode·职场和发展
m0_7381207213 小时前
渗透测试——Djinn1靶场详细渗透提权过程讲解(绕过黑名单限制,命令执行反弹shell,pyc反编译,代码白盒分析,python沙盒逃逸)
开发语言·python·php
web守墓人13 小时前
【go语言】go语言实现go-torch, 完成Lenet-5的搭建,训练,以及pth和onnx模型导出
开发语言·后端·golang
TEC_INO13 小时前
Linux50:ROCKX+RV1126视频流检测人脸
开发语言·前端·javascript
平凡但不平庸的码农14 小时前
Go 语言常用标准库详解
开发语言·后端·golang
ximu_polaris14 小时前
设计模式(C++)-行为型模式-访问者模式
c++·设计模式·访问者模式
下载居14 小时前
Node.js(Javascript运行环境) 26.1
开发语言·javascript·node.js
范什么特西14 小时前
第一个Mybatis
java·开发语言·mybatis