程序运行时产生的数据属于临时数据,程序一旦运行结束都会被释放
通过文件可以将数据持久化
C++文件操作需要包含头文件 <fstream>
文件类型分类:
文本文件: 文件以文本的ASCII码形式储存在计算机中
二进制文件:文件以文本的二进制形式储存在计算机中,用户一般不能直接读懂
文件操作分类:① ofstream:写 ② ifstream:读 ③ fstream:读写
一、文本文件
读写文件步骤:
#include<iostream>
using namespace std;
#include<string>
#include<fstream> //包含头文件
void fstreamTest()
{
//写文件操作
ofsteam ofs; // 创建流对象
if(ofs.open("test.txt",ios::out)) //打开文件 open("文件路径",打开方式);
{
ofs<<"写入数据"; // 写数据
ofs.close(); // 关闭文件
}
//读文件操作
ifsteam ifs; //创建流对象
if(ifs.open("test.txt",ios::in)) //打开文件
{
//读数据
//读文件方法一:
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 << endl;
//关闭文件
ofs.close();
}
}
文件打开方式:
二、二进制文件
打开方式指定为 ios:binary
写文件:利用流对象调用函数成员 write
写函数原型:ostream& write(const char * buffer,int len) ; (buffer:内存中一段储存空间,len:字节数)
读文件:利用流对象调用函数成员 read
读函数原型:istream& read(char * buffer,int len) ; (buffer:内存中一段储存空间,len:字节数)
#include<iostream>
using namespace std;
#include<fstream>
class Person
{
public:
char m_cName[64];
int m_nAge;
};
int main()
{
//写二进制文件
//创建流对象
ofstream ofs;
if(ofs.open("person.txt",ios::out|ios::binary))
{
//写文件
Person p = {"TEST",18};
ofs.write((const char *)&p,sizeof(Person));
//关闭文件
ofs.close();
}
//读二进制文件
ifstream ifs;
if(ifs.open("person.txt",ios::in|ios::binary))
{
//读文件
Person p;
ifs.read((char *)&p,sizeof(Person));
cout << "name:" << p.name << "age:" << p.age;
//关闭文件
ofs.close();
}
system("pause");
return 0;
}