An equivelent to CFile::Write(); Object serilization

本文介绍了一种在C++中实现对象序列化的方法,并通过一个具体的例子展示了如何将类实例写入文件以及从文件中读取的过程。该方法利用了输入输出流操作符重载来实现对象到字节流的转换。


I have a struct

ExpandedBlockStart.gifContractedBlock.gifstruct Sdot.gif{
InBlock.gif
string Str;
InBlock.gif
int Score;
ExpandedBlockEnd.gif}

None.gif
None.gif

to store personal info. In VC++ 6.0, I can use CFile::Write() to those struct instances, corresponding to individual personal info, into hard disk file.

However, in a pure C++ framework, how to do this,
 tha answer is Object Serialization The following is the example code from a post by Mark in www.codeproject.com

// Another simple example - Your class should probably have a constructor!  #include <string>#include <iostream>using namespace std;dot.gif class S{   
  string Str;   
  int Value;
  public:   
    friend ostream& operator<< (ostream& os, S& s);   
      friend istream& operator>> (istream& is, S& s);
}; 
ostream& operator<< (ostream& os, S& s){   
os << s.Str;   os.put('\n');   
os.write((char *)&s.Value, sizeof(int));   
return os;} 
istream& operator>> (istream& is, S& s){  
 is >> s.Str;   
is.get();   
is.read((char *)&s.Value, sizeof(int));   
return is;
}
 dot.gif
// Write an S object   
 S s;   
ofstream myfile("c:\\testmyfile.ext" , ios::binary : ios::trunc);   
myfile << s;
dot.gif
// Read an S object   
 S s;   
ifstream myfile("c:\\testmyfile.ext" , ios::binary);   
myfile >> s;
None.gif


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值