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();
}
相关推荐
向上_503582912 分钟前
配置Protobuf输出Java文件或kotlin文件
android·java·开发语言·kotlin
njidf4 分钟前
C++中的观察者模式
开发语言·c++·算法
IAUTOMOBILE5 分钟前
C++ 入门基础:开启编程新世界的大门
java·jvm·c++
艾莉丝努力练剑14 分钟前
alarm系统调用的一次性原理揭秘
linux·运维·服务器·开发语言·网络·人工智能·学习
-许平安-15 分钟前
MCP项目笔记七(插件 calculator)
c++·笔记·json·plugin·mcp
莱歌数字23 分钟前
元学习的核心思想
人工智能·科技·学习·制造·cae
探序基因25 分钟前
安装空间转录组分析软件-R包SPATA2的安装
开发语言·r语言
春日见36 分钟前
E2E自驾规控30讲:环境搭建
开发语言·驱动开发·matlab·docker·计算机外设
210Brian37 分钟前
嘉立创EDA硬件设计与实战学习笔记(二):元件符号与封装的绘制
大数据·笔记·学习
念何架构之路42 分钟前
Go语言表达式的求值顺序
开发语言·后端·golang