Author: Tomas Rutkauskas
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:
1 TClassRec = record2 classname: string[10];
3 pupils: TStringlist; // which contains the ID-strings of each pupil4 end;
5 6 //Answer:7 8 //Pupils in an instance of the record above contains only a Pointer, the address of 9 the actual object, and saving that is worse than useless. You need to add code to10 save the objects data. I would create a TWriter for the stream, that makes life a
11 bit easier:
12 13 14 Stream := TFileStream.Create(Filename, fmCreate);
15 try16 Writer := TWriter.Create(Stream, 4096);
17 try18 writer.WriteInteger(Classlist.Count);
19 for I := 0 to ClassList.Count - 1 do20 begin21 ClassRec := ClassList[i];
22 Writer.WriteString(classrec^.classname);
23 Writer.WriteString(classrec^.pupils.text);
24 end;
25 finally26 Writer.Free;
27 end;
28 finally29 Stream.Free
30 end;
31 32 33 //The reading part needs to be modified accordingly, using a TReader in this case.34 35 36 Stream := TFileStream.Create(Filename, fmOpenread or fmShareDenyWrite);
37 try38 Reader := TReader.Create(Stream, 4096);
39 try40 numRecords := Reader.readInteger;
41 for I := 1 to numRecords do42 begin43 New(classrec);
44 classrec^.classname := Reader.readString;
45 classrec^.pupils := TStringlist.Create;
46 classrec^.pupils.text := Reader.readString;
47 Classlist.Add(classrec);
48 end;
49 finally50 Reader.Free;
51 end;
52 finally53 Stream.Free
54 end;