通过文件可以将数据持久化
C++中对文件操作需要包含头文件
文件类型分为两种:
1,文本文件
2,二进制文件
操作文件的三大类
写操作:ofstream
读操作:ifstream
读写操作:fstream
eg:
#include<fstream>
#include<iostream>
using namespace std;
fstream ofs;//定义一个流
void test()
{
ofs.open("text.txt",ios::out);
ofs<<"name:zhangsan"<<endl;
ofs<<"sex:man"<<endl;
ofs<<"age:18"<<endl;
ofs.close();//写操作
ofs.open("text.txt",ios::in);
if(!ofs.is_open())
{
cout<<"fail"<<endl;
}
char buf[1024];//1
while(ofs>>buf)
{
cout<<buf<<endl;
}
/*2 char buf[1024]={0};
while(cute.getline(buf,sizeof(buf)))
{
cout<<buf<<endl;
}
*/
/*3 string buf;
while(getline(cute,buf))
{
cout<<buf<<endl;
}
*/
/*4char c;
while((c=cute.get())!=EOF)//EOF:end of file
{
cout<<c;
}*/
ofs.close();//读操作
}
int main()
{
test();
return 0;
}
二进制文件
#include<iostream>
#include<fstream>
using namespace std;
fstream cute;
class target
{
public:
char m_name[128];
int m_age;
};
void test()
{
target p={"zhangsan",18};
cute.open("cute.txt",ios::out|ios::binary);
cute.write((const char*)&p,sizeof(p));
cute.close();
cute.open("cute.txt",ios::in|ios::binary);
if(!cute.is_open())
{
cout<<"fail"<<endl;
return;
}
target p1;
cute.read((char*)&p1,sizeof(target));
cout<<p1.m_name<<p1.m_age<<endl;
cute.close();
}
void test2()
{
cute.open("cute.txt",ios::in|ios::binary);
if(!cute.is_open())
{
cout<<"fail"<<endl;
return;
}
target p1;
cute.read((char*)&p1,sizeof(target));
cout<<p1.m_name<<p1.m_age<<endl;
cute.close();
}
int main()
{
test();
//test2();
return 0;
}