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();
}
相关推荐
froginwe111 小时前
Rust 文件与 IO
开发语言
liulilittle1 小时前
LIBTCPIP 技术探秘(tun2sys-socket)
开发语言·网络·c++·信息与通信·通信·tun
yyy(十一月限定版)1 小时前
c++(3)类和对象(中)
java·开发语言·c++
落羽凉笙1 小时前
Python基础(4)| 玩转循环结构:for、while与嵌套循环全解析(附源码)
android·开发语言·python
ytttr8731 小时前
MATLAB的流体动力学与热传导模拟仿真实现
开发语言·matlab
山上三树1 小时前
详细介绍 C 语言中的 #define 宏定义
c语言·开发语言·算法
测试游记1 小时前
基于 FastGPT 的 LangChain.js + RAG 系统实现
开发语言·前端·javascript·langchain·ecmascript
DYS_房东的猫1 小时前
写出第一个程序
c++
小罗和阿泽2 小时前
java 【多线程基础 三】
java·开发语言
ulias2122 小时前
AVL树的实现
开发语言·数据结构·c++·windows