2007. március 29., csütörtök

How to save and load a TList with records and TStrings objects


Problem/Question/Abstract:

I know how to load and save following like records in a TList container with filestream, but how can I load and save records like this:

TClassRec = record
  classname: string[10];
  pupils: TStringlist; // which contains the ID-strings of each pupil
end;

Answer:

Pupils in an instance of the record above contains only a Pointer, the address of the actual object, and saving that is worse than useless. You need to add code to save the objects data. I would create a TWriter for the stream, that makes life a bit easier:


Stream := TFileStream.Create(Filename, fmCreate);
try
  Writer := TWriter.Create(Stream, 4096);
  try
    writer.WriteInteger(Classlist.Count);
    for I := 0 to ClassList.Count - 1 do
    begin
      ClassRec := ClassList[i];
      Writer.WriteString(classrec^.classname);
      Writer.WriteString(classrec^.pupils.text);
    end;
  finally
    Writer.Free;
  end;
finally
  Stream.Free
end;

    
The reading part needs to be modified accordingly, using a TReader in this case.


Stream := TFileStream.Create(Filename, fmOpenread or fmShareDenyWrite);
try
  Reader := TReader.Create(Stream, 4096);
  try
    numRecords := Reader.readInteger;
    for I := 1 to numRecords do
    begin
      New(classrec);
      classrec^.classname := Reader.readString;
      classrec^.pupils := TStringlist.Create;
      classrec^.pupils.text := Reader.readString;
      Classlist.Add(classrec);
    end;
  finally
    Reader.Free;
  end;
finally
  Stream.Free
end;

Nincsenek megjegyzések:

Megjegyzés küldése