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();
}
相关推荐
墨迹的陌离5 分钟前
【Linux】重生之从零开始学习运维之主从MGR高可用
学习
Dream it possible!17 分钟前
LeetCode 面试经典 150_数组/字符串_O(1)时间插入、删除和获取随机元素(12_380_C++_中等)(哈希表)
c++·leetcode·面试·哈希表
小一亿18 分钟前
【0基础PS】PS工具详解--直接选择工具
学习·平面·adobe·信息可视化·传媒·photoshop
意疏20 分钟前
浙江大学PTA程序设计C语言基础编程练习题6-10
c语言·开发语言
AI必将改变世界25 分钟前
【软考系统架构设计师备考笔记5】 - 专业英语
java·开发语言·人工智能·笔记·系统架构·英语
listhi52029 分钟前
Python实现信号小波分解与重构
开发语言·python·重构
骑驴看星星a1 小时前
层次分析法代码笔记
开发语言·笔记·python·numpy
日 近 长 安 远1 小时前
[学习笔记-AI基础篇]04_chatGPT原理和发展
笔记·学习·chatgpt
PaperFly2 小时前
📘 C++ 中成员函数与普通函数的地址是否唯一?
c++
kebeiovo2 小时前
C++实现线程池(3)缓存线程池
开发语言·c++