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;
}
相关推荐
凤年徐23 分钟前
【数据结构初阶】单链表
c语言·开发语言·数据结构·c++·经验分享·笔记·链表
oioihoii26 分钟前
C++11 右值引用:从入门到精通
开发语言·c++
阿阳微客2 小时前
Steam 搬砖项目深度拆解:从抵触到真香的转型之路
前端·笔记·学习·游戏
木子.李3474 小时前
排序算法总结(C++)
c++·算法·排序算法
freyazzr6 小时前
C++八股 | Day2 | atom/函数指针/指针函数/struct、Class/静态局部变量、局部变量、全局变量/强制类型转换
c++
fpcc6 小时前
跟我学c++中级篇——理解类型推导和C++不同版本的支持
开发语言·c++
终焉代码7 小时前
STL解析——list的使用
开发语言·c++
Chef_Chen7 小时前
从0开始学习R语言--Day18--分类变量关联性检验
学习
DevangLic7 小时前
【 *p取出内容 &a得到地址】
c++
鑫鑫向栄8 小时前
[蓝桥杯]修改数组
数据结构·c++·算法·蓝桥杯·动态规划