Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

save CString in a file

Status
Not open for further replies.

ceodav

Programmer
Feb 21, 2003
106
IT
Hi,
i'd like to save in a binary file a struct like this:

struct SComm
{
CString str1;
CString str2;
CString str3;
unsigned short sh1;
BOOL A1;
CString str4;
CString str5;
};

ok now if i write in a file

SComm c;

file.Write(&c, sizeof(SComm));

it seems ok but if i read it by opening the file as binary i don't get the strings but a series of bad caracters.

i know i can convert CString in char and it will work but i want to know if it is possible work with CString elements.


thanks

Davide
 
I'm not sure if this is what you're talking about, but you can access individual elements of the CString object just like a char array if that's what you're talking about:

CString str = "MyName";
char ch = (char)str[2];
//should return 'N';

bdiamond
 
Think of the nature of the CString. It has a pointer to a character buffer which it allocates dynamically. When you do a Write, it will copy the address of the pointer and simply ignore what it's pointing to, so that won't work at all. Just make a function to write and read that struct and you should be fine. Since you are using MFC, I'll assume you are using CArchive to do the saving. You can use the << operator to save a CString in this way and it will work correctly.
 
Actually i'm not using CArchive because it is unknown to me until now...

Before saveing i copy the CString in a char [256] and i save it. the opposite when i load it from file.

I want to ask you...what do you mean with the operator <<?

i saw in MSDN this example

CFile theFile;
theFile.Open(..., CFile::modeWrite);
CArchive archive(&theFile, CArchive::store);

but how to pass the structure?


thanks
D.
 
archive << [your structure] (think of it as cout to the archive)

bdiamond
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top