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();
}
相关推荐
paterWang1 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑1 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
饮长安千年月2 小时前
Linksys WRT54G路由器溢出漏洞分析–运行环境修复
网络·物联网·学习·安全·机器学习
红花与香菇2____2 小时前
【学习笔记】Cadence电子设计全流程(二)原理图库的创建与设计(上)
笔记·嵌入式硬件·学习·pcb设计·cadence·pcb工艺
mit6.8242 小时前
[实现Rpc] 通信类抽象层 | function | using | 解耦合设计思想
c++·网络协议·rpc
我真不会起名字啊2 小时前
“深入浅出”系列之杂谈篇:(3)Qt5和Qt6该学哪个?
开发语言·qt
laimaxgg2 小时前
Qt常用控件之单选按钮QRadioButton
开发语言·c++·qt·ui·qt5
水瓶丫头站住2 小时前
Qt的QStackedWidget样式设置
开发语言·qt
小钊(求职中)3 小时前
Java开发实习面试笔试题(含答案)
java·开发语言·spring boot·spring·面试·tomcat·maven
一天八小时4 小时前
Docker学习进阶
学习·docker·容器