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

Serialization in non - Document/View arch. projects .

By , 28 Jun 2002
 

Introduction

This article will show you how you can serialize data to disk and retrieve it again in non doc/view architecture projects. Just follow the steps outlined.

Steps to follow

  • Create a normal project as you usually do.
  • Add the class which you would use to serialize the data. It might contain just normal variables or collection classes or any kind of data that you want to store.
    • Be sure to derive that class from CObject. Only then you can serialize the data.
    • Be sure to use the DECLARE_SERIAL macro inside.
  • //CInfo.h
    
    class CInfo : public CObject
    {
    DECLARE_SERIAL(CInfo)
    
    public:
    
        virtual void Serialize(CArchive& ar);
        int m_nIndex;
        CString m_strName;
    };
  • Add the serialization function in this class's .cpp file. Be sure to use the IMPLEMENT_SERIAL macro as shown.
  • //CInfo.cpp
    
    #include "stdafx.h"
    #include "CInfo.h"
    
    IMPLEMENT_SERIAL(CInfo,CObject,1)
    
    void CInfo::Serialize(CArchive& ar)
    {
        if (ar.IsLoading()) // If you are loading data from the disk
        {
            ar >> m_strName;
            ar >> m_nIndex;
        }
        else // If you are storing data to the disk
        {
            ar << m_strName;
            ar << m_nIndex;
        }
    }
  • As this example is concerned with just 2 variables, assume that 2 edit controls have been created to accommodate the Index and the Name. Add 2 variables to those edit controls using the Class Wizard. Now the File to which the data has to be written or read from has to be defined. I do that simply by :-
  • // The Accounts.dat file is the 
    // file that we are going to use 
    // to save and read data
    
    #define DATA_FILE _T("Accounts.dat") 
    
  • Now, we write the code for storing the data to the disk. Here, m_bCanSave is declared in the header file as BOOL m_bCanSave; and in the constructor it has been initialized as m_bCanSave = FALSE;
  • void SaveRecords()                  
    //  Code to serialize and save the data
    {
        UINT nFlags = CFile::typeBinary | CFile::modeWrite;
    
        if (_access(DATA_FILE, 0))
        {
            nFlags |= CFile::modeCreate;            
            // The file doesn't exist, so create it
            
            m_bCanSave = TRUE;
        }
        else
        {
            int nTemp = _access(DATA_FILE, 6);  
            // Check Read Write Permissions
    
            if(nTemp==0)
                m_bCanSave = TRUE;
        }
    
        if (m_bCanSave)
        {
            CFile file;
            CFileException fe;
    
            // The file exists with read & write permissions
            if (file.Open(DATA_FILE, nFlags, &fe))
            {
                CArchive ar(&file, CArchive::store);
                UpdateData(TRUE);
                Info.m_nIndex = m_nIndex;
                Info.m_strName = m_strName;
                Info.Serialize(ar); // Serialize the data
            }
        }   
    }
    
  • Now , we write the code for reading the data from the disk.
  • void LoadRecords()
    {
        if (_access(DATA_FILE, 6)==0) // If File Exists
        {
            CFile file;
            CFileException fe;
    
            if (file.Open(DATA_FILE,CFile::typeBinary | 
                CFile::modeRead, &fe))
            {
                CArchive ar(&file, CArchive::load);
                Info.Serialize(ar);
            }
    
        }
    
        m_nIndex = Info.m_nIndex;
        m_strName = Info.m_strName;
        UpdateData(FALSE);
    }

Conclusion

That's it. A Simple tutorial for serialization is complete. You have a program that can serialize data to the disk and retrieve it later. You didn't know that serialization was so easy. Did you? All Luck and have a nice time.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

VGirish
Founder
India India
Member
No Biography provided

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

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Question2Tb Virtual Diskmembernhchmg27 Jun '11 - 20:26 
I test on 2TB Virtual Disk,it simulate a 2TB disk,1024,2048,4096 bytes/secotr,this app can not work.I found it on http://www.2tdisk.com
GeneralWriting to Text file .Unable to write if the file is openmemberDivya Lalwani8 Mar '09 - 21:02 
Hi,
I need to write string data data from EditBox to a Text File.
I use the following code and works fine only when WeightValue.txt file is closed.

CStdioFile fil;
CFileException e;
if(fil.Open("WeightValue.txt",CFile::modeCreate|CFile::modeWrite, &e) != FALSE)
{
fil.WriteString(filevalue);
fil.Close();
}
 
I am unable to write to WeightValue.txt if this file is kept open at program execution time.i.e string from edit box is not written to WeightValue.txt if this file is open.
Can u please tell me how to write data to a text file when it is open and closed.
Thanks and Regards.
Divya
Questionserializing file through HTTP?memberxxhimanshu30 Oct '03 - 19:39 
Confused | :confused: Confused | :confused: Hi,
I am developing an application where i need to serialize the XML files, which I have on my local hard disk with the XML files at my server. I am also using Rijndael algorithm to encrypt the files. Please suggest me how to go ahead with it as i don't have any idea on serializing data.. I want to mirror all the changes st server XML files to the local ones. If i can do it when the files are encrypted is the best. If not then I have to decrypt and then modify it..by serializing..and then encrypt it..again.. Please help me out..
Any help or pointers are highly apprecaited..I am using MFC..for doing the same..
Thanks a lot in advance..
Regards,
 
Himanshu
Generalhelpmemberannim annuar6 Oct '03 - 16:27 
how to derive CObject from dialog base and to use DECLARE_SERIAL
GeneralNice!memberRavi Bhavnani3 Jun '03 - 2:51 
Also see this[^] series of articles for serializing without having to derive from CObject.
 
/ravi
 
Let's put "civil" back in "civilization"
Home | Articles | Freeware | Music
ravib@ravib.com

GeneralHelp Serializing files over HTTP??memberxxhimanshu30 Oct '03 - 19:48 
Confused | :confused: Confused | :confused: Hi,
I am developing an application where i need to serialize the XML files, which I have on my local hard disk with the XML files at my server. I am also using Rijndael algorithm to encrypt the files. Please suggest me how to go ahead with it as i don't have any idea on serializing data.. I want to mirror all the changes st server XML files to the local ones. If i can do it when the files are encrypted is the best. If not then I have to decrypt and then modify it..by serializing..and then encrypt it..again.. Please help me out..
Any help or pointers are highly apprecaited..I am using MFC..for doing the same..
Thanks a lot in advance..
Regards,
 
Himanshu
GeneralRe: Help Serializing files over HTTP??memberRavi Bhavnani31 Oct '03 - 2:53 
If your server allows you to PUT files, you can use the MFC internet classes (CHTTPFile and others) to transfer the file to your server.
 
At the very least, the server should allow you to POST requests, in which case you can send your file's data using my Web Resource Provider class. The class allows you to encapsulate the "send my file" request as a simple API call.
 
Hope this helps.
 
/ravi
 
Let's put "civil" back in "civilization"
Home | Articles | Freeware | Music
ravib@ravib.com

GeneralRe: Help Serializing files over HTTP??memberxxhimanshu31 Oct '03 - 20:28 
Hi,
Thanks for your reply. I am already using HTTP to get the files from the server but i need those files to be updated on a daily basis and downloading daily the file makes the process very slow because the size of file becomes in MB's. So i want a way to serialize data from the server file to the local file and reflect just the changes in it and dont download the complete file..Please help..me...i need this to be done..Any help or pointers are highly appreciated..Also there are no good tutorials of file serialing and then too through HTTp..i cud not find any good tutorials where i can understand to the entirety..how serialization can be used in this case..i am using XML files and MFC..xml file serialization is possible in .NET but not in MFC..please show me a way..
Thanks a lot in advance..Confused | :confused: Confused | :confused:
 
himanshu
GeneralRe: Help Serializing files over HTTP??memberRavi Bhavnani1 Nov '03 - 5:16 
xxhimanshu wrote:
reflect just the changes in it and dont download the complete file
 
That makes sense. But I suspect this is a service that will need to be provided by the server, which will perhaps need to keep two or more versions of the data, in order to provide you with just a diff.
 
/ravi
 
Let's put "civil" back in "civilization"
Home | Articles | Freeware | Music
ravib@ravib.com

Generaldeleting recordmemberdudic20 Mar '03 - 9:10 
how can I delete some record from a file?
I write to the file name, description, date. so, I load information from a file and now I have to delete some record.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 29 Jun 2002
Article Copyright 2002 by VGirish
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid