Author: Jonas Bilinkevicius
How to read/ write a variable length string from/ to a TFileStream
Answer:
Solve 1:
1 procedure WriteStringToFS(const s: string; const fs: TFileStream);
2 var3 i: integer;
4 begin5 i := 0;
6 i := Length(s);
7 if i > 0 then8 fs.WriteBuffer(s[1], i);
9 end;
10 11 function ReadStringFromFS(const fs: TFileStream): string;
12 var13 i: integer;
14 s: string;
15 begin16 i := 0;
17 s := '';
18 fs.ReadBuffer(i, SizeOf(i));
19 SetLength(s, i);
20 fs.ReadBuffer(s, i);
21 Result := s;
22 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.
23 Stream := TMemoryStream.Create; {Or whatever kind of stream}24 Writer := TWriter.Create(Stream, 1024);
25 Reader := TReader.Create(Stream, 1024);
26 27 //Once that's done, try something similar to the following...28 29 procedure TForm1.WriteStringToFS(const S: string; Writer: TWriter);
30 begin31 try32 Writer.WriteString(S);
33 except34 raise;
35 end;
36 end;
37 38 function TForm1.ReadStringFromFS(Reader: TReader): string;
39 begin40 try41 Result := Reader.ReadString;
42 except43 raise;
44 end;
45 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.