C ++ MFC programming notes: day07 file operations, serialization, and storage of MFC, mfcday07
An MFC File Operation
1. Related Classes
CFile class-APIs that encapsulate file handles and Operating Files.
CFileFind class-provides the file search function.
2 usage of the CFile class
2.1 Open or create a file
CFile: Open
2.2 file read/write
Note: 1 file pointer Location 2 Exception Handling
CFile: Write
CFile: Read
CFile: SeekToBegin
2.3 close a file
CFile: Close
2.4 set/obtain file attributes
CFile: SetStatus/GetStatus
3 use of the CFileFind class
3.1 start searching. The returned value indicates whether a file exists.
CFileFind: FindFile
3.2 obtain the information of the first file and return whether the next file exists.
CFileFind: FindNextFile
3.3 obtain file information and determine file information
CFileFind: GetXXX/IsXXX
3.4 stop searching
CFileFind: Close
Example: 1 use this class to search for all files and folders in the C: root directory
Note: The. Directory does not exist in the disk root directory. It is only available in the next directory.
A. directory exists.
2. Use this class to search for all files and folders in C:
2.1 recursion. If it is a directory, call the function itself.
StrPath = find. GetFilePath ()
2.2 exclude. Directory
IsDots
Binary serialization
1 concept
The process of writing data to and reading data from files in sequence as a binary stream.
2 related classes
CFile class
CArchive-archive class provides specific data read/write functions.
Introduce the benefits of this class: 1. You can set the buffer during read/write; 2. Support for multiple types of data
Type.
3. read/write operations
3.1 open or create a file
CFile: Open
3.2 file read/write
3.2.1 define CArchive class objects
3.2.2 read/write Operator Functions
<Write operation
> Read operation
3.2.3 disable
3.3 close objects in the CArchive class
CFile: Close
Serialization of three objects (6th mechanisms)
Introduce Object serialization to read and write custom class objects.
1 concept
Serialized object store)
Write the class information of the object and the member variables of the object to the file in sequence.
Deserialization object (object load)
First read the class information from the file, create an object, and then read the value of the member variable for initialization.
Object process.
Conclusion: Object serialization is based on runtime class information and dynamic creation.
2. Use
2.1 define serialized classes **
2.1.1 must be a subclass of the CObject class
2.1.2 add serialized declaration macros and implementation macros
2.1.3 rewrite the virtual function CObject: Serialize. In the function, complete
Serialization of member variables in the class.
2.2 Use steps are similar to General Data
For specific read/write operations, the parameter is the object address
3 Principle
Member 3.1
_ Init_CStudent-member object of the struct type. When this object is defined
The class information of the current class is saved to the application.
Struct AFX_CLASSINIT
{
AFX_CLASSINIT (CRuntimeClass * pNewClass)
{
AfxClassInit (pNewClass );
{
// Obtain the module status information of the application class
AFX_MODULE_STATE * pModuleState = AfxGetModuleState ();
AfxLockGlobals (CRIT_RUNTIMECLASSLIST );
// Save the runtime class information of the current class (classCstudent address)
PModuleState-> m_classList.AddHead (pNewClass );
AfxUnlockGlobals (CRIT_RUNTIMECLASSLIST );
}
};
};
3.2 Object serialization Process
Ar. WriteObject (pOb );
{
// 1 obtain the runtime class information of the current class
CRuntimeClass * pClassRef = pOb-> GetRuntimeClass ();
// 2 Write the class information to the file
WriteClass (pClassRef );
{
PClassRef-> Store (* this );
{
// Write the class version, class name length, and class name to the file in sequence
WORD nLen = (WORD) lstrlenA (m_lpszClassName );
Ar <(WORD) m_wSchema <nLen;
Ar. Write (m_lpszClassName, nLen * sizeof (char ));
}
}
// 3 call the Serilize function to store the member variables of an object
(CObject *) pOb)-> Serialize (* this );
{
// First call the serialization function of the parent class
CObject: Serialize (ar );
If (ar. IsStoring () // storage operation
{
Ar <m_strName <m_nAge;
}
Else // Load Operation
{
Ar> m_strName> m_nAge;
}
}
}
3.3 deserialization of Objects
Ar. ReadObject (RUNTIME_CLASS (CStudent ));
{
// 1 read the runtime class information of the current class and obtain the address of the runtime class information variable
ReadClass (pClassRefRequested, & nSchema, & obTag );
{
// Read the class information from the file and compare and obtain the class information at runtime.
PClassRef = CRuntimeClass: Load (...)
{
// Read the class name
Ar. Read (szClassName, nLen * sizeof (char ));
// For a time-series table, locate the class information at runtime based on the class name
For (pClass = pModuleState-> m_classList; pClass! = NULL;
PClass = pClass-> m_pNextClass)
{
// Name of the specific comparison class
If (lstrcmpA (szClassName, pClass-> m_lpszClassName) = 0)
{
Return pClass;
}
}
}
}
// 2 dynamically create an object based on the obtained runtime class information
POb = pClassRef-> CreateObject ();
// 3 read the member variable from the file to initialize the new object
POb-> Serialize (* this );
{
// First call the serialization function of the parent class
CObject: Serialize (ar );
If (ar. IsStoring () // storage operation
{
Ar <m_strName <m_nAge;
}
Else // Load Operation
{
Ar> m_strName> m_nAge;
}
}
}
Program example:
Create a win32 console program, add the afxwin. h header file, and set the dynamic library containing MFC
The main program code is as follows:
// MFCfile. cpp: Defines the entry point for the console application. // # include "stdafx. h "# include <AFXWIN. h> # ifdef _ DEBUG # define new DEBUG_NEW # undef THIS_FILEstatic char THIS_FILE [] = _ FILE __; # endif // print FILE status information void show_status (CFileStatus & status) {printf ("File Name: % s \ n", status. m_szFullName); printf ("Size: % g \ n", status. m_size) ;}// print space. To clearly display the directory structure void printspace (int n) {if (n> 0) {for (int I = 0; I <n; I ++) printf ("") ;}/// File Read and Write void CFileTest () {CFile file; // define the CFile object // open CString filename = "MFCfile.txt"; BOOL bresult = file. open (filename, CFile: modeCreate | CFile: modeReadWrite); if (! Bresult) return; // if an error occurs, try {CString str = "Hello my cfile! "; File. write (str, str. getLength (); printf ("written successfully \ n"); char sztxt [100] = {0}; file. seekToBegin (); // move the file pointer to the beginning of the file. read (sztxt, 100); printf ("Read Successful, string: % s \ n", sztxt); file. close (); CFileStatus status; // if other programs are using this file, it is possible that the CFileException exception CFile: GetStatus (filename, status ); // obtain the status information show_status (status); CTimeSpan (,); // time interval, 7 days status. m_ctime-= span; // modify the creation time seven days in advance CFile: SetStatus (filename, status); // set status information} catch (CMemoryException * e) {printf ("memory error \ n");} catch (CFileException * e) {printf ("File Operation error \ n ");} catch (CException * e) {printf ("other error \ n") ;}} // file search void CFileFindTest (CString strPath, int space = 0) {CFileFind cf; BOOL result = cf. findFile (strPath + "\\*. * "); // Add the wildcard while (result) {result = cf. findNextFile (); CString filename = cf. getFileName (); printspace (space); if (cf. isDirectory () {if (! Cf. isDots () {CString filepath = cf. getFilePath (); // printf ("subdir: % s \ n", filepath); CFileFindTest (filepath, space + 1);} printf ("Directory Name: % s \ n ", filename);} else printf (" File Name: % s \ n ", filename);} cf. close () ;}// serialize (Binary), write data void CArchiveStoreTest () {CFile file; // define the CFile object // open CString filename = "MFCfile1.txt "; BOOL bresult = file. open (filename, CFile: modeCreate | CFile: modeWrite); if (! Bresult) return; // If opening fails, CArchive ar (& file, CArchive: store); ar <100 <12.46 <"hello archive! "; // Write to ar. close (); file. close () ;}// serialize (Binary), read data void CArchiveloadTest () {CFile file; // define the CFile object // open CString filename = "MFCfile1.txt "; BOOL bresult = file. open (filename, CFile: modeNoTruncate | CFile: modeRead); if (! Bresult) return; // If opening fails, CArchive ar (& file, CArchive: load); int I; double d; CString str; is returned; ar> I> d> str; // read ar. close (); file. close (); printf ("% d, % f, % s \ n", I, d, str);} // 1 defines the class CStudent that supports serialization: public CObject {public: virtual void Serialize (CArchive & ar); // rewrite the virtual function CStudent () {} CStudent (CString strName, UINT nAge) {m_strName = strName; m_nAge = nAge;} void Show () {printf ("Name: % s \ n", m_strName); printf ("Age: % d \ n", m_nAge );} public: CString m_strName; UINT m_nAge; // serialized macro DECLARE_SERIAL (CStudent)/* // macro content _ DECLARE_DYNCREATE (CStudent) AFX_API friend CArchive & AFXAPI operator> (CArchive & ar, CStudent * & pOb); */}; IMPLEMENT_SERIAL (CStudent, CObject, 1) /* // macro content CObject * PASCAL CStudent: CreateObject () {return new CStudent;} _ IMPLEMENT_RUNTIMECLASS (CStudent, CObject, 1, CStudent: CreateObject) AFX_CLASSINIT _ init_CStudent (RUNTIME_CLASS (CStudent); CArchive & AFXAPI operator> (CArchive & ar, CStudent * & pOb) {pOb = (CStudent *) ar. readObject (RUNTIME_CLASS (CStudent); return ar;} */void CStudent: Serialize (CArchive & ar) {// first call the serialization function CObject of the parent class :: serialize (ar); if (ar. isStoring () // storage operation {ar <m_strName <m_nAge;} else // loading operation {ar> m_strName> m_nAge ;}} // store the void ObjectStore (CStudent & stu) {CFile file; file. open ("C: \ stu. dat ", CFile: modeCreate | CFile: modeWrite); CArchive ar (& file, CArchive: store); ar <& stu; ar. close (); file. close () ;}// read void ObjectLoad () {CFile file; file. open ("C: \ stu. dat ", CFile: modeRead); CArchive ar (& file, CArchive: load); CStudent * pStu = NULL; ar> pStu; ar. close (); file. close (); if (pStu) {pStu-> Show () ;}} int main (int argc, char * argv []) {// CFileTest (); // CFileFindTest (".. /.. /"); CArchiveStoreTest (); CArchiveloadTest (); CStudent stu (" student1 ", 23); ObjectStore (stu); ObjectLoad (); getchar (); return 0 ;}
How to Implement mfc serialization (serialization) Storage
No existing storage methods available
We recommend that you use the boost serialization library www.boost.org/
See the serialization library tutorial dozb.bokee.com/1692310.html
VC ++ MFC CArchive class and serialization Operation Problems
Yes. The standard variable types and classes supporting serialization in MFC can all be done in this way. CString supports serialization.