c++学习第十一讲---文件操作

文件操作:

c++中对文件操作需要包含头文件 < fstream >

文本文件:以ASCII码形式储存

二进制文件:以二进制文件储存(读不懂)

操作文件三大类:

读:ifstream ; 写:ofstream ; 读写:fstream

一.文本文件:

1.写文件:

步骤:

(1)包含头文件:#include <fstream>

(2)创建流对象:ofstream ofs;

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

(4)写数据:ofs << "数据";

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

文件打开方式:

注:1.可用 | 操作符运用多种打开方式。

2.可在创建流对象的时候直接打开文件并指定打开方式:

cpp 复制代码
ofstream ofs("test.txt", ios::out | ios::binary);

例:

cpp 复制代码
void test01()
{
	ofstream ofs;
	ofs.open("test.txt", ios::out);//不写路径,默认创建在与代码项目同文件夹
	ofs << "hello world" << endl;
	ofs << "hello world" << endl;
	ofs.close();
}

2.读文件:

步骤:

(1)包含头文件:#include <fstream>

(2)创建流对象:ifstream ifs;

(3)打开文件,并判断是否打开成功:

ifs.open("文件路径",打开方式);

ifs下有一 is_open 函数,返回bool类型值。

cpp 复制代码
	if (!ifs.is_open())//这里取反
	{
		cout << "文件打开失败" << endl;
		return;
	}

(4)读数据:四种方式。

(5)关闭文件:ifs.close();

读文件的四种方式:

a.第一种:char[ ] + ifs >>

cpp 复制代码
	char buf[1024] = { 0 };
	while (ifs >> buf)//按空格和回车循环
	{
		cout << buf << endl;
	}

b.第二种:char[ ] + ifs.getline()

cpp 复制代码
	char buf[1024] = { 0 };
	while (ifs.getline(buf, sizeof(buf)))//按行循环
	{
		cout << buf << endl;
	}

c.第三种:string + getline()

cpp 复制代码
	string buf;
	while (getline(ifs, buf))
	{
		cout << buf << endl;
	}

d.第四种:char + ifs.get() (不推荐)

cpp 复制代码
	char c;
	while ((c = ifs.get()) != EOF)
	{
		cout << c;
	}

二.二进制文件:

指定打开方式为:ios::binary

1.写文件:

调用流对象的成员函数 write(const char*,写入最大字符数)

例:

cpp 复制代码
class Person
{
public:
	char m_Name[64];
	int m_Age;
};
void test03()
{
	ofstream ofs("test.txt", ios::out | ios::binary);
	Person p = { "张三",18 };
	ofs.write((const char*)(&p), sizeof(Person));
	ofs.close();
}

2.读文件:

调用流对象的成员函数 read(char*,读出最大字符数)

cpp 复制代码
class Person
{
public:
	char m_Name[64];
	int m_Age;
};
void test04()
{
	Person p;
	ifstream ifs;
	ifs.open("test.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "文件打开失败" << endl;
		return;
	}
	ifs.read((char*) & p, sizeof(Person));
	cout << p.m_Name << " " << p.m_Age << endl;
}
相关推荐
雨落倾城夏未凉25 分钟前
8.被free回收的内存是立即返还给操作系统吗?为什么?
c++·后端
雨落倾城夏未凉29 分钟前
6.new和malloc的区别
c++·后端
郝学胜-神的一滴32 分钟前
深入理解QFlags:Qt中的位标志管理工具
开发语言·c++·qt·程序人生
livemetee40 分钟前
Flink2.0学习笔记:Flink服务器搭建与flink作业提交
大数据·笔记·学习·flink
INS_KF1 小时前
【C++知识杂记2】free和delete区别
c++·笔记·学习
一只鱼^_2 小时前
牛客周赛 Round 105
数据结构·c++·算法·均值算法·逻辑回归·动态规划·启发式算法
ikkkkkkkl2 小时前
C++设计模式:面向对象设计原则
c++·设计模式·面向对象
啊阿狸不会拉杆2 小时前
《算法导论》第 27 章 - 多线程算法
java·jvm·c++·算法·图论
Easocen2 小时前
Mybatis学习笔记(五)
笔记·学习·mybatis
重启的码农2 小时前
ggml介绍 (8) 图分配器 (ggml_gallocr)
c++·人工智能·神经网络