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();
}
相关推荐
hqxstudying18 分钟前
Java行为型模式---观察者模式
java·开发语言·windows·观察者模式
DKPT22 分钟前
Java观察者模式实现方式与测试方法
java·笔记·学习·观察者模式·设计模式
CodeWithMe28 分钟前
【读书笔记】《C++ Software Design》第三章 The Purpose of Design Patterns
c++·设计模式
koooo~34 分钟前
JavaScript 与 C语言基础知识差别
c语言·开发语言·javascript
止观止37 分钟前
深入学习前端 Proxy 和 Reflect:现代 JavaScript 元编程核心
前端·javascript·学习
Attacking-Coder1 小时前
前端面试宝典---项目难点2-智能问答对话框采用虚拟列表动态渲染可视区域元素(10万+条数据)
开发语言·前端·javascript
mit6.8241 小时前
[Nagios Core] 通知系统 | 事件代理 | NEB模块,事件,回调
c语言·开发语言
mit6.8241 小时前
[Nagios Core] 事件调度 | 检查执行 | 插件与进程
c语言·开发语言·性能优化
惊骇世俗王某人1 小时前
1. 深入理解ArrayList源码
java·开发语言
Thymme1 小时前
C++获取时间和格式化时间
c++