Use serialization to read and write files

Source: Internet
Author: User

 

In many applications, we need to save or read data from the media, which involves file operations. We can use various file access methods to do this,MFC also provides a simple method for reading and writing files-"serialization ". The serialization mechanism provides developers with file control methods that are more convenient to use and transparent to byte streams through higher interface functions, for example, you can write a string to a file without worrying about the specific length. You can even operate on string arrays. With the support of classes provided by MFC that can automatically allocate memory, you can read/write data more easily. You can also compile your own class with serialization function as needed.

Serialization should be supported by classes to be serialized at the lowest level. That is to say, if you need to serialize a class, this class must support serialization. When reading and writing files through serialization, you only need the serialization function of this class.

How can classes be serialized? You need to do the following:

  • This class fromCObject is derived.
  • IncludeDECLARE_SERIAL macro definition.
  • Provides a default constructor.
  • Implement in classSerialze Function
  • UseIMPLEMENT_SERIAL indicates the class name and version number

The following code creates a simple ID card record class and supports serialization.

In H
  
Struct strPID
  
{
  
Char szName [10];
  
Char szID [16];
  
Struct strPID * pNext;
  
};
  
Class CAllPID: public CObject
  
{
  
Public:
  
DECLARE_SERIAL (CAllPID)
  
CAllPID ();
  
~ CAllPID ();
  
  
Public: // serialization related
  
Struct strPID * pHead;
  
// Other member functions
  
Void Serialize (CArchive & ar );
  
};
  
 
  
In CPP
  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.