Einzelnen Beitrag anzeigen

deccer

Registriert seit: 24. Apr 2004
Ort: Dessau
1 Beiträge
 
Delphi 7 Enterprise
 
#4

Re: Record aus stream auslesen

  Alt 24. Apr 2004, 21:48
Delphi-Quellcode:
type
  TTest = record
    A: string;
    B: string;
    C: string;
    D: integer;
    E: byte;
    F: double;
  end;

procedure WriteRecordToStream(Stream: TStream; ARecord: TTest);
var
  lLength: integer;

begin
  with ARecord do begin
    lLength := Length(A);
    Stream.Write(lLength, 4); // 4 Bytes = SizeOf(Integer)
    Stream.Write(Pointer(A)^, lLength);
    lLength := Length(B);
    Stream.Write(lLength, 4);
    Stream.Write(Pointer(B)^, lLength);
    lLength := Length(C);
    Stream.Write(lLength, 4);
    Stream.Write(Pointer(C)^, lLength);
    Stream.Write(D, 4); // 4 Bytes = SizeOf(D) = SizeOf(Integer)
    Stream.Write(E, 1); // 1 Byte = SizeOf(E) = SizeOf(Byte)
    Stream.Write(F, 8); // 8 Bytes = SizeOf(F) = SizeOf(Double);
  end;
end;

procedure ReadRecordFromStream(Stream: TStream; ARecord: TTest);
var
  lLength: integer;

begin
  with ARecord do begin
    Stream.Read(lLength, 4);
    SetLength(A, lLength);
    Stream.Read(Pointer(A)^, lLength);
    Stream.Read(lLength, 4);
    SetLength(B, lLength);
    Stream.Read(Pointer(B)^, lLength);
    Stream.Read(lLength, 4);
    SetLength(C, lLength);
    Stream.Read(Pointer(C)^, lLength);
    Stream.Read(D, 4);
    Stream.Read(E, 1);
    Stream.Read(F, 8);
  end;
end;

procedure TForm1.ButtonRecordSpeichernClick(Sender: TObject);
var
  lMS: TMemoryStream;
  lRecord: TTest;

begin
  lRecord.A := 'hallo';
  lRecord.B := 'du';
  lRecord.C := 'da';
  lRecord.D := 1000;
  lRecord.E := 255;
  lRecord.F := Now; // Now is vom typ double
  lMS := TMemoryStream.Create;
  WriteRecordToStream(lMS, lRecord);
  lMS.SaveToFile('c:\myrecord.dat');
  FreeAndNil(lMS);
end;

procedure TForm1.ButtonRecordLadenClick(Sender: TObject);
var
  lMS: TMemoryStream;
  lRecord: TTest;

begin
  lMS := TMemoryStream.Create;
  lMS.LoadFromFile('c:\myrecord.dat');
  ReadRecordFromStream(lMS, lRecord);
  FreeAndNil(lMS);
  with lRecord do
    ListBox1.Items.Add(Format('%s %s %s %d %d %3.2f', [A, B, C, D, E, F]));
end;
[edit=MrSpock]Delphi Tags eingefügt. Mfg, MrSpock[/edit]
Streite nie mit Dummen. Zuerst ziehen sie dich auf ihr Niveau herunter, dann schlagen sie dich mit ihrer Erfahrung.
  Mit Zitat antworten Zitat