Ver Mensaje Individual
  #2  
Antiguo 03-01-2006
Northern Northern is offline
Miembro
 
Registrado: ene 2006
Posts: 238
Reputación: 21
Northern Va por buen camino
TStream.WriteBuffer/ReadBuffer

Esta respuesta la da Peter Below de los TeamB a un usuario....no se si está permitido poner este tipo de mensajes
pero como soy nuevo lo pongo y si alguien tiene algo que decir que lo diga, que lo borre y todos contentos y felices


In article <[email protected]>, Bob McKinnon wrote:
> I would like to write out an array of long strings along with other data to
> a file. I tried to create a file records like I normally do but that did
> not work since I was using a string. I wonder if streams is the way to go?
> To make it simple, if I have a data object that contains two integers and
> an array of strings it easy to stream that out to file? Sample code would
> be great.
>
> Test = class (Tobject)
> x, x1 : Integer;
> StList : array [1..100] of string;
> End;

Since strings are variable-length data you need to write the length of a
string in addition to the characters to the stream, otherwise you cannot read
them back conveniently.

Lets add two methods to your Test class:
Código Delphi [-]
procedure Test.SaveToStream( aStream: TStream );
var
  len, i: Integer;
begin
  Assert( Assigned( aStream ));
  // Write the two integer fields first
  aStream.WriteBuffer( x, sizeof(x));
  aStream.WriteBuffer( x1, sizeof(x1));
  // Now write the string array. Since its size is fixed we
  // do not need to write the number of elements first.
  for i:= Low( StList ) to High( StList ) do begin
    len := Length( StList[i] );
    aStream.WriteBuffer( len, sizeof(len));
    if len > 0 then
      aStream.WriteBuffer( StList[i][1], len );
  end;
end;

procedure Test.LoadFromStream( aStream: TStream );
var
  len, i: Integer;
begin
  Assert( Assigned( aStream ));
  // Read the two integer fields first
  aStream.ReadBuffer( x, sizeof(x));
  aStream.ReadBuffer( x1, sizeof(x1));
  // Now read the string array. Since its size is fixed we
  // do not need to read the number of elements first.
  for i:= Low( StList ) to High( StList ) do begin
    aStream.ReadBuffer( len, sizeof(len));
    SetLength( StList[i], len );
    if len > 0 then
      aStream.ReadBuffer( StList[i][1], len );
  end;
end;
Since ReadBuffer and WriteBuffer use untyped parameters handing them an
Ansistring (which is a pointer type) is a bit unintuitive: you have to pass
the first character of the string to get the correct address across.

--
Peter Below (TeamB)

Última edición por vtdeleon fecha: 03-01-2006 a las 20:25:00.
Responder Con Cita