MFC file read and write operations, serialization and deserialization of classes, cfile,cfiledialog,carchive,cstdiofile

Source: Internet
Author: User
Tags object serialization save file serialization

first, use the CFileDialog file dialog box

The dialog box is simply to get the name and path of the file that will be opened or saved, and of course the suffix filter for the file. The code is as follows:

	/* Open File dialog box
	/CString Filter;//mfc String class
	filter = "Text Document (*.txt) |*.txt| |"; /File name filter
	CFileDialog DLG (true, NULL, NULL, ofn_hidereadonly, filter);//set to TRUE to open File dialog
	if (dlg. DoModal () = = IDOK)//Determine if successful click to determine
	{
		CString strpath;//file path
		strpath = dlg. GetPathName ()//Get file path
		//todo According to file path strpath you can read data </span>
		MessageBox (strpath);
	}


Save the file dialog box, only need to show the first parameter of the CFileDialog modification method is false.

two, use CArchive and CFile to read and write files

The CArchive class is a tool class for file operations, and it is easy to implement many of the features of the CFile code as follows:

	/* Read File
	/* CString filter;filter = "text document (*.txt) |*.txt| |"; /File name filter
	CFileDialog DLG (true, NULL, NULL, ofn_hidereadonly, filter);//set to TRUE to open File dialog
	if (dlg. DoModal () = = IDOK)//Determine if successful click to determine
	{
		CString strpath;//file path
		strpath = dlg. GetPathName ()//Get file path
		//todo load local file into memory
		CFile mfile;if (Mfile.open (strpath, cfile::moderead) = = 0)// Read way Open file
			return;char buf[512];//buffer is 512, I want to save the class is very small, also rarely
		CArchive ar (&mfile, Carchive::load,, buf); /create CArchive, the mode is load is read
		//ar >> str_txt;//binary Read, if it is text, read will be wrong, the first character will garbled, and sometimes file pointer out of bounds
		ar. ReadString (Str_txt)//reads the data and saves it to the Str_txt array
		//ar. Flush ()//clean buffer, write to local
		ar. Close ();
		Mfile.close ();
		MessageBox (strpath);/popup File path}
	}
</pre><pre>
	* * Save file
	/CString filter;
	Filter = "Text Document (*.txt) |*.txt| |";
	CFileDialog dlg (FALSE, NULL, NULL, ofn_hidereadonly, filter);
	if (dlg. DoModal () = = Idok)
	{
		CString strpath;
		strpath = dlg. GetPathName ();
		Todo saves the file in memory to the local
		CFile mfile;
		Mfile.open (strpath, Cfile::modecreate | Cfile::modewrite);
		CArchive ar (&mfile, carchive::store);//similar to write
		//ar << str_txt;//binary read/write
		ar. WriteString (str_txt);//string read/write
		ar. Close ();
		Mfile.close ();

		MessageBox (strpath);
	}


Three, using CStdioFile to implement simple string file operation

If you want to manipulate the file knowledge text string, and the file is small, using CStdioFile will be more convenient, the code is as follows:

	/* Read File * *
	CString filter;
	Filter = "Text Document (*.txt) |*.txt| |";
	CFileDialog dlg (TRUE, NULL, NULL, ofn_hidereadonly, filter);
	if (dlg. DoModal () = = Idok)
	{
		CString strpath;
		strpath = dlg. GetPathName ();
		CStdioFile mfile;//Simple text file read-write
		cfileexception mexcept;//file exception, I did not use
		Mfile.open (strpath, cfile::moderead);
		if (Mfile = NULL) return;
		Mfile.readstring (str_txt);
		Mfile.close ();
		MessageBox (strpath);
	}

<strong>	</strong>/* Save File * *
	CString filter;
	Filter = "Text Document (*.txt) |*.txt| |";
	CFileDialog dlg (FALSE, NULL, NULL, ofn_hidereadonly, filter);
	if (dlg. DoModal () = = Idok)
	{
		CString strpath;
		strpath = dlg. GetPathName ();
		CStdioFile Mfile;
		CFileException mexcept;
		Mfile.open (strpath, Cfile::modewrite, &mexcept);
		CString string = L "I am a string by append"; Mfile.seektoend ();//can skip to end of file, CArchive does not have this feature//
		mfile.seektobegin ();// You can skip to the beginning of the file, and CArchive does not have this feature
		mfile.writestring (string);
		Mfile.close ();
		MessageBox (strpath);
	}


four, using CArchive and Cobject.serialize () to implement object serialization and deserialization

There are two main parts, the declaration of the Serializable class, the local saving and reading of the class (serialization and deserialization).

1, declare serializable classes, divided into. h files and. cpp files, the code is as follows:

#pragma once
class Student:public CObject//First step Inherits CObject class
{public
:
	declare_serial (Student);//Part II Using macros to declare that the currently created class is a serialized class
	Student ();
	~student ();
	virtual void Serialize (carchive& archive); The third rewrite serialization method

	CString name;
	char sex;
	unsigned int age;
};
#include "stdafx.h"
#include "Student.h"

implement_serial (Student, CObject, 1)///step fourth establishes the version identity, similar to the ID, When multiple different classes are serialized, numbers do not repeat
student::student ()
{
}

student::~student ()
{
}

void Student::serialize (carchive& Archive)//step Fifth implementation serialization method
{
	cobject::serialize (archive);
	if (archive. IsStoring ())//Determine whether to write to the file is serialized
		archive << name << sex << age;//to save the property to a file
	else
		archive >> name >> sex >> age;//Read properties to program
}

2, the class is saved and read locally (serialized and deserialized), and the code is as follows:

/* Read file to program/CString filter;
	Filter = "Text Document (*.txt) |*.txt| |";
	CFileDialog dlg (TRUE, NULL, NULL, ofn_hidereadonly, filter); if (dlg.
		DoModal () = = Idok) {CString strpath; strpath = dlg.

		GetPathName ();
		Todo loads the local file into memory CFile Mfile;
		if (Mfile.open (strpath, cfile::moderead) = = 0) return;
		Char buf[512];
		CArchive ar (&mfile, carchive::load, buf); unsigned long length = ar.
		Readcount ()///Read the number of stored data units, because we are first written, so we must first read student* Stu; for (int i = 0; i < length;i++) Stu = (student*) ar. ReadObject (Runtime_class (Student))//Read a class information, while the pointer moves to the next class information to begin, we read the last AR.
		Close ();

		Mfile.close ();
	MessageBox (strpath); }
	/* Save object to file
	/* CString filter;
	Filter = "Text Document (*.txt) |*.txt| |";
	CFileDialog dlg (FALSE, NULL, NULL, ofn_hidereadonly, filter);
	if (dlg. DoModal () = = Idok)
	{
		CString strpath;
		strpath = dlg. GetPathName ();

		Todo loads the local file into memory
		CFile mfile;
		if (Mfile.open (strpath, cfile::modecreate| cfile::modewrite) = = 0)//File open mode in the middle of the use of | A vertical bar return
			;
		Char buf[512];
		CArchive ar (&mfile, Carchive::store, buf);
		Student Stu;
		Stu.age =;
		Stu.name = L "Xu Kaiwen";
		Stu.sex = ' m ';
		Ar. Writecount (1);//First write the number of data units we will write, to facilitate reading, to determine the number of
		ar. WriteObject (&stu);//write File
		ar. Close ();
		Mfile.close ();

		MessageBox (strpath);
	}


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.