Click here to Skip to main content
6,291,722 members and growing! (13,210 online)
Email Password   helpLost your password?
Languages » C / C++ Language » Beginners     Beginner License: The Code Project Open License (CPOL)

A serialization primer - Part 1

By Ravi Bhavnani

This tutorial describes how to easily serialize a simple object.
VC6, VC7Win2K, WinXP, Visual Studio, MFC, Dev
Posted:17 Feb 2002
Updated:25 Nov 2002
Views:197,062
Bookmarked:136 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
53 votes for this article.
Popularity: 7.12 Rating: 4.13 out of 5
2 votes, 6.3%
1
1 vote, 3.1%
2
4 votes, 12.5%
3
6 votes, 18.8%
4
19 votes, 59.4%
5

This article is the first of a 3 part tutorial on serialization.

  • Part 1 introduces the basics of serialization.
  • Part 2 explains how to gracefully handle reading invalid data stores and support versioning.
  • Part 3 describes how to serialize complex objects.

Serialization is the process of writing or reading an object to or from a persistent storage medium, such as a disk file. Serializing an object requires 3 ingredients:

  • A CFile object representing the datafile
  • A CArchive object that provides the serialization context
  • The object being serialized
Serialization data flow

Step 1 - Open the datafile

To serialize an object to the file "foo.dat", open the file with the appropriate access mode. In this example, the file is opened for exclusive read/write access.
  // Open file "foo.dat"
  CFile* pFile = new CFile();
  ASSERT (pFile != NULL);
  if (!pFile->Open ("foo.dat", CFile::modeReadWrite | CFile::shareExclusive)) {
      // Handle error
      return;
  }

Step 2 - Hook up the archive

Next, a CArchive object is hooked up to the file. The archive provides an efficient conduit to persistent storage. Instead of directly reading and writing the file, you serialize data to and from the archive. The archive needs to know if you're going to be using it to read or write data. In this example, we'll assume we're writing data.
  // Create archive ...
  bool bReading = false;  // ... for writing
  CArchive* pArchive = NULL;
  try
  {
    pFile->SeekToBegin();
    UINT uMode = (bReading ? CArchive::load : CArchive::store);
    pArchive = new CArchive (pFile, uMode);
    ASSERT (pArchive != NULL);
  }
  catch (CException* pException)
  {
    // Handle error
    return;
  }

Step 3 - Serialize the object

Finally, we serialize the object by calling its serialize() method. serialize() is just a method we made up. It has nothing to with MFC's CObject::Serialize(). Also, you don't have to derive your object from CObject. Our serialize() method takes a pointer to a CArchive and returns an integer status.
  int CFoo::serialize
    (CArchive* pArchive)
  {
    int nStatus = SUCCESS;

    // Serialize the object ...
    ...
    
    return (nStatus);
  }
We'll get to the actual serialization process in a minute. Meanwhile, let's recognize a couple of important points:
  • The same method CFoo::serialize() is used to read/write the object from/to persistent storage.
  • CFoo::serialize() doesn't know anything about the datafile bring accessed.
Assume CFoo represents an employee record that contains a couple of data members.
  class CFoo
  {
    // Construction/destruction
    public:
      CFoo::CFoo();
      virtual CFoo::~CFoo();

    // Methods
    public:
      int serialize (CArchive* pArchive);

    // Data members
    public:
      CString  m_strName;  // employee name
      int      m_nId;      // employee id
  };
We use CArchive's streaming operators << and >> to read/write the data members from/to the archive. CArchive knows how to serialize simple data types like int, float, DWORD, and objects like CString. The archive also knows whether it's in read or write mode. You can query its mode by calling CArchive::IsStoring(). CFoo's serialization method can then be written as:
  int CFoo::serialize
    (CArchive* pArchive)
  {
    int nStatus = SUCCESS;

    // Serialize the object ...
    ASSERT (pArchive != NULL);
    try
    {
      if (pArchive->IsStoring()) {
         // Write employee name and id
         (*pArchive) << m_strName;
         (*pArchive) << m_nId;
      }
      else {
         // Read employee name and id
         (*pArchive) >> m_strName;
         (*pArchive) >> m_nId;
      }
    }
    catch (CException* pException)
    {
      nStatus = ERROR;
    }
    return (nStatus);
  }

Step 4 - Clean up

When you've finished serializing, you should clean up by closing the archive and datafile.
  pArchive->Close();
  delete pArchive;
  pFile->Close();
  delete pFile();

Conclusion

Well, there you have it - serialization in a (very small) nutshell. In Part 2, we'll see how to gracefully handle reading invalid data stores and support different versions of our object. In Part 3, we'll see how to serialize complex objects.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ravi Bhavnani


Member
Ravi Bhavnani is an ardent fan of Microsoft technologies who loves building Windows apps, especially PIMs, system utilities, and things that go bump on the Internet. During his career, Ravi has developed expert systems, desktop imaging apps, enterprise marketing automation software, EDA tools, a platform to help people find, analyze and understand information, and trading software for institutional investors. He currently works for a company that provides advanced data visualization solutions for Microsoft technologies.

His interests include the .NET framework, reasoning systems, financial analysis and algorithmic trading, NLP, CHI and UI design. Ravi holds a BS in Physics and Math and an MS in Computer Science and is a Microsoft C# MVP. His claim to fame is that he crafted CodeProject's "joke" forum post icon.

Ravi's biggest fear is that one day he might actually get a life, although the chances of that happening seem extremely remote.
Occupation: Software Developer (Senior)
Company: Dundas Software
Location: Canada Canada

Other popular C / C++ Language articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 59 (Total in Forum: 59) (Refresh)FirstPrevNext
QuestionChanging the format of the data in the file PinmemberAORD13:26 29 Sep '07  
AnswerRe: Changing the format of the data in the file PinmemberRavi Bhavnani18:51 9 Oct '07  
GeneralAbout the contents of the file Pinmembercristitomi23:24 12 Feb '07  
AnswerRe: About the contents of the file PinmemberRavi Bhavnani2:34 13 Feb '07  
GeneralRe: About the contents of the file Pinmembercristitomi3:22 13 Feb '07  
GeneralRe: About the contents of the file PinmemberRavi Bhavnani4:25 13 Feb '07  
Generaltrouble in reading in serialized list structures Pinsussitsh1113:01 15 Dec '04  
GeneralRe: trouble in reading in serialized list structures(typo corrected) Pinmemberitsh115:11 16 Dec '04  
GeneralReading a file using serialization Pinsusshemanth_phk12:55 9 Sep '04  
GeneralRe: Reading a file using serialization PinmemberRavi Bhavnani13:28 9 Sep '04  
GeneralRe: Reading a file using serialization PinmemberThomas Mielke15:58 11 Oct '07  
GeneralCArchive and .NET PinsussDaniel S. Horwitz7:37 12 Jul '04  
GeneralIn memory serialization Pinmemberno_reg_name3:59 7 May '04  
GeneralRe: In memory serialization PinmemberRavi Bhavnani7:02 7 May '04  
GeneralSerialization using Dialog application PinmemberHybridLlama17:57 12 Jan '04  
GeneralRe: Serialization using Dialog application PinmemberRavi Bhavnani7:37 16 Jan '04  
GeneralRe: Serialization using Dialog application PinmemberHybridLlama10:56 16 Jan '04  
GeneralRe: Serialization using Dialog application PinmemberRavi Bhavnani4:32 17 Jan '04  
GeneralRe: Serialization using Dialog application PinmemberHybridLlama9:28 17 Jan '04  
GeneralDitching.NET serialization in favor of MFC PinmemberMtnBiknGuy17:49 28 Aug '03  
GeneralRe: Ditching.NET serialization in favor of MFC PinmemberRavi Bhavnani5:33 29 Aug '03  
AnswerRe: Ditching.NET serialization in favor of MFC PinmemberGordon Brandly7:48 31 Aug '05  
GeneralProblem reading file PinmemberCount Zer010:19 21 Jul '03  
GeneralRe: Problem reading file PinsussAnonymous6:43 16 Jan '04  
Generallibrary for XML serialization in C++ ? PinsussAnonymous2:15 17 Mar '03  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 25 Nov 2002
Editor: Sean Ewington
Copyright 2002 by Ravi Bhavnani
Everything else Copyright © CodeProject, 1999-2009
Web15 | Advertise on the Code Project