C++builder 保存字符串
这是我写的两个保存和打开字符串的代码
//从流中读取字符串
void OpenStringFromStream(TMemoryStream* stream,String& str)
{
int length ;
stream->LoadFromFile("C:\\Users\\Administrator\\Desktop\\123.tcs");
stream->Read(&length,sizeof(length));
char * strs = new char[length+1];
stream->Read(strs,length);
strs[length] = '\0';
str = String(strs);
ShowMessage(str);
delete[] strs;
}
void SaveStringToStream(TMemoryStream* stream, String str)
{
int length = 2*str.Length();
stream->Write(&length,sizeof(length));
stream->Write(str.c_str(),length);
stream->SaveToFile("C:\\Users\\Administrator\\Desktop\\123.tcs");
}
//从流中读取字符串
void OpenStringFromStream(TMemoryStream* stream,String& str)
{
int length ;
stream->LoadFromFile("C:\\Users\\Administrator\\Desktop\\123.tcs");
stream->Read(&length,sizeof(length));
length /= 2;//加上这一句
WideChar* strs = new WideChar[length+1];
stream->Read(strs,length);
strs[length] = L'\0';//加上这一句
str = String(strs);
ShowMessage(str);
delete[] strs;
}
void SaveStringToStream(TMemoryStream *stream, String str)
{
int length = 2 * str.Length();
stream->Write(&length, sizeof(length));
stream->Write(str.c_str(), length);
stream->SaveToFile("E:\\Temp\\123.tcs");
}
void OpenStringFromStream(TMemoryStream *stream, String &str)
{
stream->LoadFromFile("E:\\Temp\\123.tcs");
stream->Position = 0;
int length;
stream->Read(&length, sizeof(length));
WideChar *strs = new WideChar[length / 2 + 1];
stream->Read(strs, length);
strs[length / 2] = 0x0;
str = String(strs);
ShowMessage(str);
delete []strs;
}
void __fastcall TForm1::Button1Click(TObject *Sender)
{
TMemoryStream *ms = new TMemoryStream;
String src = L"不要把简单的问题复杂化,hahaha!";
SaveStringToStream(ms, src);
String dst;
OpenStringFromStream(ms, dst);
delete ms;
}