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;
}
相关推荐
津津有味道3 分钟前
Qt C++串口SerialPort通讯发送指令读写NFC M1卡
linux·c++·qt·串口通信·serial·m1·nfc
傅里叶的耶30 分钟前
C++系列(二):告别低效循环!选择、循环、跳转原理与优化实战全解析
c++·visual studio
Vitta_U1 小时前
MFC的List Control自适应主界面大小
c++·list·mfc
菜菜why1 小时前
MSPM0G3507学习笔记(一) 重置版:适配逐飞库的ti板环境配置
笔记·学习·电赛·嵌入式软件·mspm0
夜阑卧听风吹雨,铁马冰河入梦来1 小时前
Spring AI 阿里巴巴学习
人工智能·学习·spring
Dovis(誓平步青云)2 小时前
基于探索C++特殊容器类型:容器适配器+底层实现原理
开发语言·c++·queue·适配器·stack
板栗焖小鸡2 小时前
STM32-PWM驱动无源蜂鸣器
stm32·学习
Code季风2 小时前
Gin 中间件详解与实践
学习·中间件·golang·go·gin
pipip.3 小时前
UDP————套接字socket
linux·网络·c++·网络协议·udp
孞㐑¥8 小时前
Linux之Socket 编程 UDP
linux·服务器·c++·经验分享·笔记·网络协议·udp