C++学习 --文件

文件操作步骤:

1, 包含头文件#include<fstream>

2, 创建流对象:ofstream ofs

3, 打开文件:ofs.open("文件路径", 打开方式)

4, 写数据:ofs << "写入数据"

5, 关闭文件:ofs.close()

打开方式:ios::in 读文件打开, ios:out,写文件打开, ios::ate, 打开文件, 定位到尾部

ios::trunc, 如果文件存在先删除, 在创建, ios::binary, 二进制文件

1, 写文件

cpp 复制代码
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <set>
#include <fstream>

using namespace std;

void test()
{	
	ofstream aaa;
	aaa.open("test.txt", ios::out);
	aaa << "张三, 28";
	aaa.close();
}

int main()
{	
	test();

	system("pause");

	return 0;
}

2, 读文件

cpp 复制代码
ifstream aaa;
aaa.open("test.txt", ios::in);

//第一种方式
/*char buf [1024] = { 0 };
while (aaa >> buf)
{
	cout << buf;
}*/

//第二种方式
/*char buf[1024] = { 0 };
while (aaa.getline(buf, sizeof(buf)))
{
	cout << buf;
}*/

//第三种方式
/*string buf;
while (getline(aaa, buf))
{
	cout << buf;
}*/

//第四种方式
char c;
while ((c = aaa.get()) != EOF)
{
	cout << c;
}

3, 二进制文件

3-1, 写文件

cpp 复制代码
class Person
{
public:
	char m_name[64];
	int m_age;
};

void test()
{	
	Person p = { "张三", 18 };
	ofstream aaa("test1.txt", ios::out | ios::binary);
	//aaa.open("test1.txt", ios::out | ios::binary);
	aaa.write((const char*)&p, sizeof(Person));
	aaa.close();
}

3-2, 读文件

cpp 复制代码
class Person
{
public:
	char m_name[64];
	int m_age;
};

void test()
{	
	Person p;
	ifstream aaa("test1.txt", ios::out | ios::binary);
	//aaa.open("test1.txt", ios::out | ios::binary);
	aaa.read((char*)&p, sizeof(Person));
	cout << p.m_name << endl;
	cout << p.m_age << endl;
	aaa.close();
}
相关推荐
Realdagongzai1 小时前
Linux 6.19.10 内核调度器算法详解
linux·学习·算法·spring·kernel
charlie1145141911 小时前
现代C++特性指南(5)——RAII 深入理解:资源管理的基石
开发语言·c++·现代c++
xxl大卡1 小时前
Redis完整详细学习笔记
redis·笔记·学习
星夜夏空991 小时前
FreeRTOS学习(1)——裸机开发与操作系统
单片机·嵌入式硬件·学习
Cat_Rocky1 小时前
CICD-Git简单学习 操作流程后续补
git·学习
weixin_550083151 小时前
基于知识图谱的python个性化学习路径推荐系统项目源码
人工智能·学习·知识图谱
神仙别闹1 小时前
基于QT(C++)+Sqlite3实现单词消除游戏系统
c++·qt·sqlite
至为芯1 小时前
IP5356H_G3至为芯支持C口双向快充22.5W新国标移动电源方案芯片
c语言·开发语言
yunn_1 小时前
基于C++ 11的线程池实现
c++