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;
}
相关推荐
LGGGGGQ32 分钟前
嵌入式学习-PyTorch(4)-day21
学习
艾莉丝努力练剑1 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
人生游戏牛马NPC1号3 小时前
学习 Flutter (三):玩安卓项目实战 - 上
android·学习·flutter
还债大湿兄3 小时前
《C++内存泄漏8大战场:Qt/MFC实战详解 + 面试高频陷阱破解》
c++·qt·mfc
没有羊的王K6 小时前
SSM框架学习——day1
java·学习
珊瑚里的鱼6 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上6 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
Risehuxyc7 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
林林要一直努力8 小时前
AOSP Settings模块问题初窥
android·学习·bug·android studio
景彡先生9 小时前
C++编译期计算:常量表达式(constexpr)全解析
服务器·c++