Click here to Skip to main content
Click here to Skip to main content

A serialization primer - Part 1

By , 25 Nov 2002
 

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
Technical Lead
Canada Canada
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, marketing automation software, EDA tools, a platform to help people find, analyze and understand information, trading software for institutional investors and advanced data visualization solutions. He currently works for a company that provides enterprise workforce management solutions to large clients.
 
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 was a Microsoft MVP (C++ and C# in 2006 and 2007). He is also the co-inventor of 2 patents on software security and generating data visualization dashboards. 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.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4membersagar131015 Aug '12 - 20:56 
Generalthank you !membermayjune5624 Jun '12 - 18:46 
GeneralRe: thank you !memberRavi Bhavnani25 Jun '12 - 1:16 
GeneralThe links in the conclusion to the other parts are deadmemberHarrison H7 Oct '10 - 10:23 
GeneralRe: The links in the conclusion to the other parts are deadmemberRavi Bhavnani7 Oct '10 - 10:33 
GeneralRe: The links in the conclusion to the other parts are deadmemberHarrison H7 Oct '10 - 10:38 
QuestionChanging the format of the data in the filememberAORD29 Sep '07 - 12:26 
AnswerRe: Changing the format of the data in the filememberRavi Bhavnani9 Oct '07 - 17:51 
GeneralAbout the contents of the filemembercristitomi12 Feb '07 - 22:24 
AnswerRe: About the contents of the filememberRavi Bhavnani13 Feb '07 - 1:34 
GeneralRe: About the contents of the filemembercristitomi13 Feb '07 - 2:22 
GeneralRe: About the contents of the filememberRavi Bhavnani13 Feb '07 - 3:25 
Generaltrouble in reading in serialized list structuressussitsh1115 Dec '04 - 12:01 
GeneralRe: trouble in reading in serialized list structures(typo corrected)memberitsh1116 Dec '04 - 4:11 
GeneralReading a file using serializationsusshemanth_phk9 Sep '04 - 11:55 
GeneralRe: Reading a file using serializationmemberRavi Bhavnani9 Sep '04 - 12:28 
GeneralRe: Reading a file using serializationmemberThomas Mielke11 Oct '07 - 14:58 
GeneralCArchive and .NETsussDaniel S. Horwitz12 Jul '04 - 6:37 
GeneralIn memory serializationmemberno_reg_name7 May '04 - 2:59 
GeneralRe: In memory serializationmemberRavi Bhavnani7 May '04 - 6:02 
GeneralSerialization using Dialog applicationmemberHybridLlama12 Jan '04 - 16:57 
GeneralRe: Serialization using Dialog applicationmemberRavi Bhavnani16 Jan '04 - 6:37 
Store the data in an object, then serialize the object.
 
/ravi
 
My new year resolution: 2048 x 1536
Home | Articles | Freeware | Music
ravib@ravib.com

GeneralRe: Serialization using Dialog applicationmemberHybridLlama16 Jan '04 - 9:56 
GeneralRe: Serialization using Dialog applicationmemberRavi Bhavnani17 Jan '04 - 3:32 
GeneralRe: Serialization using Dialog applicationmemberHybridLlama17 Jan '04 - 8:28 
GeneralDitching.NET serialization in favor of MFCmemberMtnBiknGuy28 Aug '03 - 16:49 
GeneralRe: Ditching.NET serialization in favor of MFCmemberRavi Bhavnani29 Aug '03 - 4:33 
AnswerRe: Ditching.NET serialization in favor of MFCmemberGordon Brandly31 Aug '05 - 6:48 
GeneralProblem reading filememberCount Zer021 Jul '03 - 9:19 
GeneralRe: Problem reading filesussAnonymous16 Jan '04 - 5:43 
Questionlibrary for XML serialization in C++ ?sussAnonymous17 Mar '03 - 1:15 
AnswerRe: library for XML serialization in C++ ?memberRavi Bhavnani17 Mar '03 - 1:30 
AnswerRe: library for XML serialization in C++ ?memberRodrigo Pinho Pereira de Souza16 Aug '05 - 3:22 
GeneralNewbie Question using CStdioFilememberGregggggg23 Jan '03 - 16:55 
GeneralRe: Newbie Question using CStdioFilememberRavi Bhavnani4 Mar '03 - 4:44 
GeneralForget MFC CArchive/CFile...memberTBiker13 Jan '03 - 18:38 
GeneralRe: Forget MFC CArchive/CFile...memberZac Howland3 Feb '03 - 6:18 
GeneralA General question about SerializationmemberNaresh25_cool23 Dec '02 - 1:19 
GeneralRe: A General question about SerializationsussAnonymous24 Dec '02 - 22:12 
GeneralRe: A General question about SerializationmemberRavi Bhavnani28 Dec '02 - 4:16 
GeneralRe: A General question about SerializationmemberZac Howland3 Feb '03 - 6:20 
GeneralA word of warningsussAnonymous18 Dec '02 - 21:51 
GeneralMore warnings...memberPeter Weyzen8 Jan '03 - 11:14 
GeneralThis is good.memberMarc Clifton15 Dec '02 - 13:58 
GeneralSerializing Multiple Object Types To Same FilememberMangesh Sardesai4 Dec '02 - 21:01 
GeneralRe: Serializing Multiple Object Types To Same FilememberRavi Bhavnani5 Dec '02 - 1:14 
GeneralRe: Serializing Multiple Object Types To Same FilememberMangesh Sardesai5 Dec '02 - 2:23 
GeneralRe: Serializing Multiple Object Types To Same FilememberRavi Bhavnani5 Dec '02 - 5:14 
Generali likememberumeflying4 Dec '02 - 20:25 
GeneralCObjectmemberKarstenK27 Nov '02 - 0:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 25 Nov 2002
Article Copyright 2002 by Ravi Bhavnani
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid