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



I have a struct

struct S{
string Str;
int Score;
}



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; 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;
}
 
// Write an S object   
 S s;   
ofstream myfile("c:\\testmyfile.ext" , ios::binary : ios::trunc);   
myfile << s;
// Read an S object   
 S s;   
ifstream myfile("c:\\testmyfile.ext" , ios::binary);   
myfile >> s;


posted on 2007-05-06 16:01  cy163  阅读(...)  评论(...编辑  收藏

导航