文件操作
程序运行时产生的数据都属于临时数据,程序一旦运行结束都会被释放
文件操作可以 使数据持久化
头文件<fstream>
文件类型分为两种:
- 文本文件:文件以文本的ASCII码形式存储在计算机中
- 二进制文件:文件以文本的二进制形式存储在计算机中,用户一般不能直接读懂它们
操作文件的三大类:
ofstream 写操作
ifstream 读操作
fstream 读写操作
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// 文件读写操作
// 写文件
void test01()
{
ofstream ofs; // 创建流对象
ofs.open("test01.txt", ios::out);
ofs<<"Name: Alex"<<endl;
ofs<<"Age: 29"<<endl;
ofs<<"Gender: Man"<<endl;
ofs.close();
}
// 读文件
void test02()
{
ifstream ifs;
ifs.open("test01.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)
{
cout<<c;
}
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
二进制读写文件
写文件
打开方式指定为 ios::binary
二进制方式写文件主要利用流对象调用成员函数 write
函数原型:
ostream & write (const char * buffer, int len);
参数解释:字符指针 buffer 指向内存中一段存储空间,len是读写的字节数
读文件
二进制方式读文件主要利用流对象调用成员函数 read
函数原型:
istream & read (char * buffer, int len);
#include <iostream>
#include <fstream>
using namespace std;
// 二进制文件读写操作
// 写文件
class Person
{
public:
char m_Name[64];
int m_Age;
};
void test01()
{
ofstream ofs;
ofs.open("person.txt", ios::out | ios::binary);
// ofstream ofs("person.txt", ios::out | ios::binary);
Person p = {"Egon", 21};
ofs.write((const char *)&p, sizeof(Person));
ofs.close();
}
// 读文件
void test02()
{
ifstream ifs;
ifs.open("person.txt", ios::in | ios::binary);
if(!ifs.is_open())
{
cout<<"文件打开失败"<<endl;
return;
}
Person p;
ifs.read((char *)&p, sizeof(Person));
cout<<"Name: "<<p.m_Name<<" Age: "<<p.m_Age<<endl;
ifs.close();
}
int main()
{
// test01();
test02();
system("pause");
return 0;
}