Author: Jonas Bilinkevicius
How to read/ write a variable length string from/ to a TFileStream
Answer:
Solve 1:
1 2 procedure WriteStringToFS(const s: string; const fs: TFileStream);
3 var4 i: integer;
5 begin6 i := 0;
7 i := Length(s);
8 if i > 0 then9 fs.WriteBuffer(s[1], i);
10 end;
11 12 function ReadStringFromFS(const fs: TFileStream): string;
13 var14 i: integer;
15 s: string;
16 begin17 i := 0;
18 s := '';
19 fs.ReadBuffer(i, SizeOf(i));
20 SetLength(s, i);
21 fs.ReadBuffer(s, i);
22 Result := s;
23 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.
24 25 Stream := TMemoryStream.Create; {Or whatever kind of stream}26 Writer := TWriter.Create(Stream, 1024);
27 Reader := TReader.Create(Stream, 1024);
28 29 Once that's done, try something similar to the following...
30 31 procedure TForm1.WriteStringToFS(const S: string; Writer: TWriter);
32 begin
33 try
34 Writer.WriteString(S);
35 except
36 raise;
37 end;
38 end;
39 40 function TForm1.ReadStringFromFS(Reader: TReader): string;
41 begin
42 try
43 Result := Reader.ReadString;
44 except
45 raise;
46 end;
47 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.