Articles   Members Online:
-Article/Tip Search
-News Group Search over 21 Million news group articles.
-Delphi/Pascal
-CBuilder/C++
-C#Builder/C#
-JBuilder/Java
-Kylix
Member Area
-Home
-Account Center
-Top 10 NEW!!
-Submit Article/Tip
-Forums Upgraded!!
-My Articles
-Edit Information
-Login/Logout
-Become a Member
-Why sign up!
-Newsletter
-Chat Online!
-Indexes NEW!!
Employment
-Build your resume
-Find a job
-Post a job
-Resume Search
Contacts
-Contacts
-Feedbacks
-Link to us
-Privacy/Disclaimer
Embarcadero
Visit Embarcadero
Embarcadero Community
JEDI
Links
How to read/ write a variable length string from/ to a TFileStream Turn on/off line numbers in source code. Switch to Orginial background IDE or DSP color Comment or reply to this aritlce/tip for discussion. Bookmark this article to my favorite article(s). Print this article
20-Oct-02
Category
OO-related
Language
Delphi 2.x
Views
132
User Rating
No Votes
# Votes
0
Replies
0
Publisher:
DSP, Administrator
Reference URL:
DKB
			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   var
3     i: integer;
4   begin
5     i := 0;
6     i := Length(s);
7     if i > 0 then
8       fs.WriteBuffer(s[1], i);
9   end;
10  
11  function ReadStringFromFS(const fs: TFileStream): string;
12  var
13    i: integer;
14    s: string;
15  begin
16    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  begin
31    try
32      Writer.WriteString(S);
33    except
34      raise;
35    end;
36  end;
37  
38  function TForm1.ReadStringFromFS(Reader: TReader): string;
39  begin
40    try
41      Result := Reader.ReadString;
42    except
43      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.

			
Vote: How useful do you find this Article/Tip?
Bad Excellent
1 2 3 4 5 6 7 8 9 10

 

Advertisement
Share this page
Advertisement
Download from Google

Copyright © Mendozi Enterprises LLC