我在这里读了很多关于将字符串写入TMemoryStream、保存到文件并将字符串读取回TMemoryStream 的讨论
我不知道我在这里做错了什么,但我的SaveData或LoadData都错了。我可以在调用SaveData之前检查Title的值,它保存了我所期望的内容。但是,当我调用LoadData并检查Title的值时,它是垃圾。有人能告诉我我做错了什么吗?
procedure SaveData(FileName: TFileName);
var
MemStr: TMemoryStream;
Title: String;
begin
MemStr:= TMemoryStream.Create;
try
MemStr.Seek(0, soFromBeginning);
WriteStreamStr( MemStr, TItle );
MemStr.SaveToFile(FileName);
finally
MemStr.Free;
end;
end;
procedure LoadData(FileName: TFileName);
var
MemStr: TMemoryStream;
Title: String;
begin
MemStr:= TMemoryStream.Create;
try
MemStr.LoadFromFile(FileName);
MemStr.Seek(0, soFromBeginning);
Title := ReadStreamStr( MemStr );
finally
MemStr.Free;
end;
end;
procedure WriteStreamInt(Stream : TStream; Num : integer);
{writes an integer to the stream}
begin
Stream.WriteBuffer(Num, SizeOf(Integer));
end;
procedure WriteStreamStr(Stream : TStream; Str : string);
{writes a string to the stream}
var
StrLen : integer;
begin
{get length of string}
StrLen := Length(Str);
{write length of string}
WriteStreamInt(Stream, StrLen);
if StrLen > 0 then
{write characters}
Stream.Write(Str[1], StrLen);
end;
function ReadStreamInt(Stream : TStream) : integer;
{returns an integer from stream}
begin
Stream.ReadBuffer(Result, SizeOf(Integer));
end;
function ReadStreamStr(Stream : TStream) : string;
{returns a string from the stream}
var
LenStr : integer;
begin
Result := '';
{get length of string}
LenStr := ReadStreamInt(Stream);
{set string to get memory}
SetLength(Result, LenStr);
{read characters}
Stream.Read(Result[1], LenStr);
end;
使用时
Stream.Write(Str[1], StrLen);
您正在向流写入第一个StrLen
字节。但是(unicode)字符串数据实际上是StrLen * SizeOf(Char)
字节(您必须考虑char类型的大小)。所以以下应该起作用:
Stream.Write(Str[1], StrLen * SizeOf(Str[1]));
从流中读回数据时也是如此。