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
Files Operation
Language
Delphi 2.x
Views
146
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   
2   procedure WriteStringToFS(const s: string; const fs: TFileStream);
3   var
4     i: integer;
5   begin
6     i := 0;
7     i := Length(s);
8     if i > 0 then
9       fs.WriteBuffer(s[1], i);
10  end;
11  
12  function ReadStringFromFS(const fs: TFileStream): string;
13  var
14    i: integer;
15    s: string;
16  begin
17    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.

			
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