C++语言对文件的处理有一些限制,对于后来出现的一些语言,如Pascal 和Java都提供了对对象进行序列化的支持,而C++只能通过C FILE s结构 或 C++自己的fstream 类来保存程序中变量的值。
二进制序列化
对象序列化包含保存对象中的某些值,这些值是来自类当中的成员变量。在目前的标准当中,C++不存在内在的对象序列化,为了达到对象序列化,可以用二进制序列化来实现。
如果你想保存一个值到文件,fstream 类提供了以二进制形式保存该值的方法。当你想用二进制的形式保存一个变量,在定义ofstream变量的时候,要指定iso::binary.
例子如下:
将对象保存在stream
#include <fstream>
#include <iostream>
using namespace std;
class Student
{
public:
char FullName[40];
char CompleteAddress[120];
char Gender;
double Age;
bool LivesInASingleParentHome;
};
int main()
{
Student one;
strcpy(one.FullName, "Ernestine Waller");
strcpy(one.CompleteAddress, "824 Larson Drv, Silver Spring, MD 20910");
one.Gender = 'F';
one.Age = 16.50;
one.LivesInASingleParentHome = true;
ofstream ofs("fifthgrade.ros", ios::binary);
ofs.write((char *)&one, sizeof(one));
return 0;
}
从stream流中读取对象
#include <fstream>
#include <iostream>
using namespace std;
class Student
{
public:
char FullName[40];
char CompleteAddress[120];
char Gender;
double Age;
bool LivesInASingleParentHome;
};
int main()
{
/* Student one;
strcpy(one.FullName, "Ernestine Waller");
strcpy(one.CompleteAddress, "824 Larson Drv, Silver Spring, MD 20910");
one.Gender = 'F';
one.Age = 16.50;
one.LivesInASingleParentHome = true;
ofstream ofs("fifthgrade.ros", ios::binary);
ofs.write((char *)&one, sizeof(one));
*/
Student two;
ifstream ifs("fifthgrade.ros", ios::binary);
ifs.read((char *)&two, sizeof(two));
cout << "Student Information\n";
cout << "Student Name: " << two.FullName << endl;
cout << "Address: " << two.CompleteAddress << endl;
if( two.Gender == 'f' || two.Gender == 'F' )
cout << "Gender: Female" << endl;
else if( two.Gender == 'm' || two.Gender == 'M' )
cout << "Gender: Male" << endl;
else
cout << "Gender: Unknown" << endl;
cout << "Age: " << two.Age << endl;
if( two.LivesInASingleParentHome == true )
cout << "Lives in a single parent home" << endl;
else
cout << "Doesn't live in a single parent home" << endl;
cout << "\n";
return 0;
}