2006. április 11., kedd

How to read/ write a variable length string from/ to a TFileStream


Problem/Question/Abstract:

How to read/ write a variable length string from/ to a TFileStream

Answer:

Solve 1:

procedure WriteStringToFS(const s: string; const fs: TFileStream);
var
  i: integer;
begin
  i := 0;
  i := Length(s);
  if i > 0 then
    fs.WriteBuffer(s[1], i);
end;

function ReadStringFromFS(const fs: TFileStream): string;
var
  i: integer;
  s: string;
begin
  i := 0;
  s := '';
  fs.ReadBuffer(i, SizeOf(i));
  SetLength(s, i);
  fs.ReadBuffer(s, i);
  Result := s;
end;


Solve 2:

You should be using TWriter and TReader. They make this kind of thing really simple to do. Create a stream, writer and reader object at the form level, then instantiate them in the OnCreate and destroy them in the OnDestroy event.

Stream := TMemoryStream.Create; {Or whatever kind of stream}
Writer := TWriter.Create(Stream, 1024);
Reader := TReader.Create(Stream, 1024);

Once that's done, try something similar to the following...

procedure TForm1.WriteStringToFS(const S: string; Writer: TWriter);
begin
  try
    Writer.WriteString(S);
  except
    raise;
  end;
end;

function TForm1.ReadStringFromFS(Reader: TReader): string;
begin
  try
    Result := Reader.ReadString;
  except
    raise;
  end;
end;

No need to save the length of the string because the writer do this automatically. The only caveat is that you need to be sure to create the stream first and to destroy it last.

Nincsenek megjegyzések:

Megjegyzés küldése