Einzelnen Beitrag anzeigen

Sequitar

Registriert seit: 8. Jan 2016
74 Beiträge
 
Delphi 10.4 Sydney
 
#8

AW: einlesen eines String aus einem TFileStream

  Alt 3. Nov 2021, 21:12
Kleine Demo (phne pchars)

Delphi-Quellcode:
program savemystringtoastream;

{$APPTYPE CONSOLE}
{$R *.res}

uses classes,
  System.SysUtils;

procedure teststring_tostream;
var
  f: tstream;
  atext, atext2: string;
  len: byte;

begin

  try
    f := tmemorystream.Create;
    f.Position := 0; // optional here
    atext := 'mytest';
    len := length(atext); // 6
    f.write(len, sizeof(len)); // +1
    f.write(atext[1], length(atext) * sizeof(char)); // +2*6

    // init
    f.Position := 0;
    len := 0;
    atext2 := '';
    f.Read(len, sizeof(len)); // get length from stream
    setlength(atext2, len); // allocate new string
    f.Read(atext2[1], len * sizeof(char));
    assert(atext = atext2);
    atext := '';
    atext2 := '';
  finally
    f.free; { TODO -oUser -cConsole Main : Insert code here }

  end;

end;

begin
  teststring_tostream;

end.
Kann u.U. aber für sehr lange strings lange dauern. Daher hatte ich mir hierfür mal einen helper geschrieben, der das mit tbytes und readbuffer sehr zügig löst.


Delphi-Quellcode:
Type
 Tlargefile_reader_base = Class(TInterfacedObject, Ilargefileimporter)
  Private
  Private
    Content: Tbytes;
    Fendianess: Tendianess;
    Fchunksize: Tfilereadchunksize;
  Private
//..
end;
//..
Procedure Tlargefile_reader_base.Loadstream(Stream: Tstream;
  Endianess: Tendianess = Bigendian);
Begin
  Setlength(Content, Stream.Size);
  Stream.Position := 0;
  If Endianess = Bigendian Then
    Stream.ReadBuffer(Content, Stream.Size) // standard little endian
  Else
    Raise Exception.Create('Loading Little-Endian coded files not implemented');
  Fendianess := Endianess;
End;


Procedure Tlargefile_reader_base.Setastext(Atext: String);
Var
  P: Pchar;
  C: PByte;
  Max: Pchar;
Begin
  Setlength(Content, Length(Atext));
  Max := @Atext[Length(Atext)]; // last element
  P := @Atext[1];
  C := @Content[0];
  While P <> Max Do
  Begin
    C^ := Ord(P^);
    Inc(C);
    Inc(P);
    
  End;
  // last element
 
  C^ := Ord(P^);
  // Inc(C);
  // Inc(P);
End;


Function Tlargefile_reader_base.Getastext: String;
Var
  C: PByte;
  P: Pchar;
  Max: PByte;
Begin
  // Result := Utils.Bytestostr(content);
  Max := @Content[High(Content)]; // last element
  Setlength(Result, Length(Content));
  P := @Result[1];
  C := @Content[0];
  // for c in self.content do
  While C <> Max Do
  Begin
    P^ := Char(C^);
    Inc(P);
    Inc(C, Bytesize);
  End;
  // last element
  P^ := Char(C^);
End;

Geändert von Sequitar ( 3. Nov 2021 um 21:27 Uhr)
  Mit Zitat antworten Zitat