Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strings in streams. 2

Status
Not open for further replies.

Slippie

Programmer
Jan 17, 2006
6
0
0
ZA
How do you use strings in TMemoryStreams?

The strings are not fixed lengths.

The first thing in my stream is an integer containing the number of different strings.
Each string is then stored in the following manner:

First the SizeOf(String) and then string itself using the
SizeOf(String) as the byte count.

Reading strings is done in the same manner.

There are to many problems to mention them all, but basically the same one never occurs twice in a row. They are all memory read errors.

Is there a better way or do I just have to get my code in order?
 

Use Length(String) and access the string as String[1].

Code:
To write:

var
  S : AnsiString;
Stream.Write(Length(S), SizeOf(integer));
Stream.Write(S[1], Length(S));

Code:
To read:

var
  L : integer;
  S : AnsiString;
Stream.Read(L, SizeOf(integer));
SetLength(S, L);
Stream.Read(S[1], L);

buho (A).

 

Note: check your strings first. S[1] will cause and AV if S = '' (Length(S) = 0).

buho (A).
 
Is there any particular reason you want to use TMemoryStream for strings ?

TStringList is a very flexible component and will probably give you everything you need without the need for any extra coding.

Andrew
Hampshire, UK
 
The TStringList was the way to go. It also sports the very nice commands SaveToStream and LoadFromStream.

Tnx a lot.

Slippie
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top