CString is a class, not a plain old data (POD) type so it behaves differently. The MFC way to deal with this is serialization. All MFC classes derived from CObject support serialization. This is a means of taking all the typically hierarchical data stored in a class structure and converting it to a linear format more appropriate for storing in a stream. You can lookup MSDN help on serialization for more information.
Another approach is to convert the CString to POD types then store those in your file. Since CString is just a bunch of functions for string manipulation and a string buffer, a CString's complete state can be defined by the contents of it's buffer. The buffer is nothing more than a NULL terminated array of characters (either char or wchar_t depending on UNICODE settings--both POD types). You can go about this one of two ways: store an integral value representing the lenght of the string, then the characters themselves (this is sort-of how CString's internal Serialize() function works), or store all the characters and include the NULL terminator. There are advantages and disadvantages to both, so chose whichever is appropriate.
A simple implementation based on your code might look like this (added code in green):
Code:
void CFileOperationsDlg::OnBnClickedButton1()
{
this->UpdateData (TRUE);
CFile f;
CFileException Fexcep;
test buffWrite;
test buffRead;
size_t sz;
TCHAR *buf;
buffWrite .age ="27";
buffWrite .name = "My Name";
f.Open ("E:\\MyFile.bcr", CFile ::modeCreate | CFile ::modeWrite ,&Fexcep);
sz=buffWrite.GetLength();
f.Write(&sz,sizeof(size_t));
f.Write(buffWrite.GetBuffer(),sz*sizeof(TCHAR));
//f.Write (&buffWrite,sizeof(buffWrite ));
buffWrite.ReleaseBuffer();
f.Close ();
if(f.Open("E:\\MyFile.bcr", CFile ::modeRead ,&Fexcep) == FALSE)
return;
try
{
f.Read(&sz,sizeof(size_t);
buf=new TCHAR[sz+1];
f.Read(buf,sz*sizeof(TCHAR));
buf[sz]=0;
buffRead.SetString(buf);
delete[] buf;
//f.Read (&buffRead ,sizeof(buffRead ));
}
catch(CException *e)
{
e->AssertValid ();
}
f.Close ();
}