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;
}
相关推荐
感哥2 小时前
C++ std::set
c++
侃侃_天下3 小时前
最终的信号类
开发语言·c++·算法
博笙困了3 小时前
AcWing学习——差分
c++·算法
2303_Alpha4 小时前
SpringBoot
笔记·学习
萘柰奈4 小时前
Unity学习----【进阶】TextMeshPro学习(三)--进阶知识点(TMP基础设置,材质球相关,两个辅助工具类)
学习·unity
青草地溪水旁4 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁4 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
感哥4 小时前
C++ std::vector
c++
zl_dfq4 小时前
C++ 之【C++11的简介】(可变参数模板、lambda表达式、function\bind包装器)
c++
沐矢羽4 小时前
Tomcat PUT方法任意写文件漏洞学习
学习·tomcat