将字符串写入TMemoryStream

时间:2013-02-11 15:21:53

标签: delphi stream memorystream

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

1 个答案:

答案 0 :(得分:19)

使用时

Stream.Write(Str[1], StrLen);

您正在向流中写入StrLen个字节。但是(unicode)字符串数据实际上是StrLen * SizeOf(Char)个字节(您必须考虑char类型的大小)。以下应该有效:

Stream.Write(Str[1], StrLen * SizeOf(Str[1]));

从流中读回数据时相同。