Serializing Str with MFC CArchive

Web Site  Methods

The methods and operations in this group are available only when MFC is included in the project. They are designed to allow the programmer to use the familiar << and >> operators with CArchive objects, just like basic types (int, double, etc.) and like MFC CString.

 
Str::ReadString
 
static BOOL ReadString (CArchive& ar, Str& dest)

This static method will read the contents of a Str object from the passed stream ar, and store it in dest. The previous data in dest is destroyed.

When read from and written to CArchive streams, Str objects are binary compatible with the format of MFC CString, so streams can be used interchangeably between programs using either string class.

ReadString can read both Unicode and ANSI strings from the stream, regardless of the current mode in which the library is compiled. However, if a Unicode string is found and the platform does not support Unicode, an exception will be thrown.

The method always returns TRUE. If an error occurs (premature end of file), an MFC exception will be thrown.

 

 
Str::WriteString
 
static void WriteString (CArchive& ar, const STRCHAR* lpsz)

This static method will write out a string to the passed stream. The input string is passed as const STRCHAR*, so both Str objects (through implicit typecast) and plain C-style strings can be passed.

This method will write out the string as Unicode or ANSI, depending on the current library mode.

 

 

Str::operator >>
Str::operator <<

 
friend CArchive& operator << (CArchive& ar, const Str& source)
friend CArchive& operator >> (CArchive& ar, Str& dest)

These two operators are just wrappers around ReadString and WriteString. They allow the developer to manipulate Str objects with a clean and familiar syntax.

Example: Write an int and a string to an output stream

	// Example needs MFC to compile
	CArchive arc(&mfcfile, CArchive::store);
	int v_int = 7;
	Str v_str(_T("Sample text"));
	arc << v_int << v_str;

 

See also: Windows-specific