Use MFC's CFile file classes and CArchive serialization classes for binary file read and write operations

Source: Internet
Author: User
Tags class definition readfile serialization
A programming case Introduction
This case is based on the console project, create a specialized demo class CDemo, realize the binary file read and write serialization operation, the specific code is as follows:
1 CDemo class Definition:
Class CDemo
{
Public
void CreateFile ();
CDemo ();
Virtual ~cdemo ();

void Serialize (CArchive &ar);
void WriteFile ();
void ReadFile ();
void Initlize ();//initialization
Private
Presentation data to read and write:

Base type Data
int nyear;
Char Chmonth;
Short Shday;
float fsalary;

String data
CString M_strusername;
CString M_strpassword;

FILE-related data:
CString m_strfilename;//filename
};
2 CDemo class interface implementation definition:

Cdemo::cdemo ()
{
Read-Write file name
M_strfilename = "Data.dat";

}

Cdemo::~cdemo ()
{

}
File read and write serialization function
void Cdemo::serialize (CArchive &ar)
{
if (AR. IsStoring ())
{
Write variable data to file
ar<<nyear;
ar<<chmonth;
ar<<shday;
ar<<fsalary;
ar<<m_strusername;
ar<<m_strpassword;
}
Else
{
Read the contents of the file and save it to a variable:
ar>>nyear;
ar>>chmonth;
ar>>shday;
ar>>fsalary;
ar>>m_strusername;
ar>>m_strpassword;

}
}


Data Write file
void Cdemo::writefile ()
{
CFile file;
if (file. Open (M_strfilename, Cfile::modewrite, NULL))//Create disk File and open
{
CArchive ar (&file, carchive::store);//Create a file serialization object based on the open file
Serialize (AR); Write file content

Close object after end
Ar. Close ();
File. Close ();
}
}


Reading data from a file
void Cdemo::readfile ()
{
CFile file;

if (file. Open (M_strfilename, Cfile::moderead, NULL))//opening disk File
{
CArchive ar (&file, carchive::load);//Create a file serialization object based on the open file
Serialize (AR); Read the contents of the file

Close object after end
Ar. Close ();

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.