编程语言
首页 > 编程语言> > C++ 第五章 文件操作

C++ 第五章 文件操作

作者:互联网

程序运行时产生的数据都属于临时数据,程序一旦运行结束会被释放
通过文件可以将数据持久化
C++中对文件操作需要包含头文件< fstream >
文件类型分为两种:

  1. 文本文件:文件以文本的ASCII码形式存储在计算机中
  2. 二进制文件:文件以二进制形式存储在计算机中,人不能直观阅读数据
    操作文件的三大类:
  3. ofstream:写文件
  4. ifstream:读文件
  5. fstream:读写操作

一、写入文件

步骤

  1. 包含头文件fstream
  2. 创建流对象 ofstream ofs;
  3. 打开文件 ofs.open("文件路径",打开方式);
  4. 写数据 ofs<<"data";
  5. 关闭文件 ofs.close();

二、文件打开方式

打开方式 解释
ios::in 为读文件而打开文件
ios::out 为写文件而打开文件
ios::ate 初始位置:文件尾
ios::app 追加方式写文件
ios::trunc 如果文件存在,先删除再创建
ios::binary 二进制方式

注意:文件打开方式可以配合使用,利用|操作符

三、读取文件

步骤

  1. 包含头文件fstream
  2. 创建流对象 ifstream ifs;
  3. 打开文件 ifs.open("文件路径",打开方式);
  4. 读数据 ifs>>data;
  5. 关闭文件 ifs.close();

查看是否打开文件

使用ifs.is_open()或ifs.failed()

读入数据的方式

第一种

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;
}

四、二进制文件

打开方式为ios::binary

1.写文件

二进制方式写文件主要利用流对象调用成员函数write
函数原型 ostream& write(const char * buffer,int len);
参数解释:字符指针buffer指向内存中一段地址空间,len是读写的字节数

2.读文件

二进制方式读取文件主要利用流对象调用成员函数read
函数原型 istream& read(char *buffer,int len);
参数解释:字符指针buffer指向内存中一段地址空间,len是读写的字节数

3.示例代码

class person
{
public:
	int age;
	char name[64];
	person(const char name[], int age)
	{
		strcpy_s(this->name, name);
		this->age = age;
	}
	person()
	{

	}
};
ostream& operator<<(ostream& cout, person& p)
{
	cout << p.name << " " << p.age;
	return cout;
}
int main()
{
	person p1("Mike", 18);
	ofstream ofs("1.txt", ios::out | ios::binary);
	ofs.write((const char*)&p1, sizeof(person));
	ofs.close();
	
	ifstream ifs("1.txt", ios::in | ios::binary);
	if (!ifs.is_open())
	{
		cout << "文件读取失败" << endl;
		return 0;
	}
	person p;
	ifs.read((char*)&p, sizeof(person));
	cout << p << endl;
	ifs.close();
	return 0;
}

标签:文件,ifs,ios,C++,char,第五章,buf,打开方式
来源: https://www.cnblogs.com/zjq182/p/15757878.html