#include<iostream>
#include<string>
#include<fstream>
using namespace std;
class Test
{
private:
string str;
int a;
public:
Test();
Test(string str,int a);
void SaveTest();
};
Test::Test()
{
str="\0";
}
Test::Test(string str,int a)
{
this->a=a;
this->str=str;
}
void Test::SaveTest()
{
fstream outfile,infile;
outfile.open("TestFile.txt",ios::out|ios::binary);
if(!outfile)
{
cout<<"打开系统文件失败!1\n";
abort();
}
outfile.write((char*)this,sizeof(Test));//<<this->a<<this->str;
outfile.close();
infile.open("TestFile.txt",ios::in|ios::binary);
if(!infile)
{
cout<<"打开系统文件失败!2\n";
abort();
}
Test *t = new Test();
infile.read((char*)(t),sizeof(Test));
cout<<t->a<<t->str<<endl;
infile.close();
outfile.open("TestFile.txt",ios::out|ios::app|ios::binary);
if(!outfile)
{
cout<<"打开系统文件失败!3\n";
abort();
}
Test *tes = new Test("hi hi me?", 11);
outfile.write((char*)tes,sizeof(Test));
outfile.close();
infile.open("TestFile.txt",ios::in|ios::binary);
if(!infile)
{
cout<<"打开系统文件失败!4\n";
abort();
}
int i;
Test* tt[2];
for(i=0;i<2;i++)
{
tt[i] = new Test();
infile.read((char*)tt[i],sizeof(Test));
cout<<tt[i]->a<<tt[i]->str;
}
infile.close();
}
void main()
{
Test *test = new Test("hello hei!",12);
test->SaveTest();
}
--------------------------------------------------------------------------------------------------------------
最好使用建立在栈上的类即new所得,让程序最后析构。。。