我在这里阅读了很多关于将字符串写入 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;