Write the length with
CString::GetLength()
and then write the char array in
CString
. You can access the null terminated array by casting
CString
to
LPCTSTR
.
CString str;
int len=str.GetLength()+1;
fwrite((const void*)(&len), sizeof(int), 1, fp); fwrite((const void*)(LPCTSTR)str, sizeof(TCHAR), len, fp);
Note:
CString::GetLength()
does not include the
NULL
char at the end, so you have to add one if you want to write the NULL char as well.
When reading, read the length 1st and then the char array. Do not read more than the length! Since array is null terminated, you can just do this.
int len=0;
fread((void*)(&len), sizeof(int), 1, fp); TCHAR* pbuf = new TCHAR[len];
fread((void*)(pbuf), sizeof(TCHAR), len, fp); CString str = pbuf; delete [] pbuf;
pbuf = NULL;
Or you can avoid the extra memory allocation by calling
CString::GetBuffer
.
int len=0;
fread((void*)(&len), sizeof(int), 1, fp); CString str;
LPTSTR* pbuf = str.GetBuffer(len);
fread((void*)(pbuf), sizeof(TCHAR), len, fp); str.ReleaseBuffer();