0
点赞
收藏
分享

微信扫一扫

【c++】文件操作

互联网码农 2022-03-30 阅读 97

目录

1.写文件

2.读文件

3.二进制文件


文件类型分为:

  • 文本文件:以ASCII的形式存储
  • 二进制文件:以文本二进制的形式存储

操作文件的三大类:

  • 1.ofstream:写操作
  • 2.ifstream:读操作
  • 3.fstream:读写操作

1.写文件(o)

步骤如下:

1.包含头文件--#include<fstream>

2.创建流对象--ofstream ofs;

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

//也可以在创建对象的时候就指定文件路径和打开方式

4.写数据--ofs<<"写入的数据";

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

打开方式如下图(主要记住第一、二和最后一个):

 注意:两种方法一起配合使用,利用|操作符

eg:ios::binary|ios::out

写文件如下:

#include<iostream>
using namespace std;
#include<fstream>
void text()
{
	ofstream ofs;
 //ofstream ofs("text.txt", ios::out);
	ofs.open("text.txt", ios::out);
	ofs << "臭屁烊" << endl;
	ofs << "要好好照顾自己哟!" << endl;
	ofs << "要努力见你!" << endl;
	ofs.close();
}
int main()
{
	text();
	system("pause");
	return 0;
}

右击项目便可以查看该文件所在文件夹,可以发现如果不指定具体位置,便会在该项目所在的文件夹

 

2.读文件(i)

步骤如下:

1.包含头文件---include<fstream>

2.创建流对象---ifstream ifs;

3.打开文件并判断文件是否打开成功---ifs.open("文件路径",打开方式)--返回的是bool型;

4.读数据---四种方式(推荐前三种)

5.关闭文件---if.close();

如下:

#include<iostream>
using namespace std;
#include<fstream>
#include<string>
void text()
{
	ifstream ifs;
	ifs.open("text.txt", ios::in);//打开文件
	//判断文件是否打开
	if (!ifs.is_open())
	{
		cout << "文件打开失败!"<<endl;
     return;
	}
	//读数据
	//第一种
	/*char buf[1024] = { 0 };
	while (ifs >> buf)
	{
		cout << buf << endl;
	}*/
	//第二种
	/*char buf[1024] = { 0 };
	while (ifs.getline(buf, sizeof(buf)))
	{
		cout << buf << endl;
	}*/
	//第三种
	/*string buf;
	while (getline(ifs, buf))
	{
		cout << buf << endl;
	}*/
	//第四种
	char c;
	while ((c = ifs.get()) != EOF)//EOF--end of file
	{
		cout << c;
	}
	ifs.close();

}
int main()
{
	text();
	system("pause");
	return 0;
}

3.二进制文件

打开方式要指定:iOS::binary

1.写文件(ofs.write)

#include<iostream>
using namespace std;
#include<fstream>
class person{
public:
	char m_name[64];
	int m_age;
};
void text()
{
	//打开文件
	ofstream ofs("text.txt", ios::out|ios::binary);
	person p = { "易烊千玺", 21 };
	//写入文件
	ofs.write((const char *)&p, sizeof(p));
  ofs.close();
}
int main()
{
	text();
	system("pause");
	return 0;
}

查看文件如图所示:

可以发现二进制的方式写入会出现乱码

2.读文件

#include<iostream>
using namespace std;
#include<fstream>
class person{
public:
	char m_name[64];
	int m_age;
};
void text()
{
	//打开文件
	ifstream ifs("text1.txt", ios::in | ios::binary);

	//判断是否打开
	if (!ifs.is_open())
	{
		cout <<"打开文件失败!"<< endl;
		return;
	}
	//读文件
	person p;
	ifs.read((char *)&p, sizeof(p));
	cout << "姓名:" << p.m_name << "年龄:" << p.m_age << endl;
  ifs.close();
}
int main()
{
	text();
	system("pause");
	return 0;
}

可以发现读文件没有问题。

今天的学习就到这了!!!

举报

相关推荐

C++——文件操作

文件操作(c/c++)

C++ 文件操作

c++文件操作

C++文件操作

C++系列-文件操作

0 条评论