Author: Tomas Rutkauskas
I am trying to work out how to store approximately 1000 lines of text (3 columns,
30 chars each) inside an application. I do not want to have any .INI entries and
would prefer not to use an external file.
Answer:
You can start with one and embed it into a resource. Let's assume you have the data
in a normal textfile. Make a resource script file (filedata.rc) with a line like
FILEDATA RCDATA filedata.txt
Add this RC file to your Delphi 5 project group. This automatically gets you a $R
line for it in the project DPR file and the resource is compiled for you when you
build the project. Now, how to get at the data at runtime? Each line is a fixed
length of 90 characters. So the file could be represented as an array of records of
this type:
1 type2 TFileData = packedrecord3 col1, col2, col3: array[1..30] of Char;
4 crlf: array[1..2] of Char;
5 end;
6 PFileData = ^TFileData;
7 8 Let's use a class to regulate access to the data. I assume you only need to read
9 it, so there is no need to copy it from the resource.
10 11 type
12 TDatahandler = class
13 private
14 FData: TList;
15 FResHandle: THandle;
16 function GetRecord(index: Integer): TFileData;
17 procedure GetRecordCount: Integer;
18 procedure InitDatalist;
19 public
20 constructor Create;
21 destructor Destroy; override;
22 property Records[index: Integer]: TFileData read GetRecord;
23 property Recordcount: Integer read GetRecordcount;
24 end;
25 26 implementation
27 28 constructor TDatahandler.Create;
29 begin
30 inherited;
31 FData := TList.Create;
32 InitDatalist;
33 end;
34 35 destructor TDatahandler.Destroy;
36 begin
37 Fdata.Free;
38 if FResHandle <> 0 then
39 begin
40 UnlockResource(FResHandle);
41 FreeResource(FResHandle);
42 end;
43 inherited;
44 end;
45 46 function TDatahandler.GetRecord(index: Integer): TFileData;
47 begin
48 Result := PFileData(FData[i])^;
49 end;
50 51 procedure TDatahandler.GetRecordCount: Integer;
52 begin
53 Result := FData.Count;
54 end;
55 56 procedure TDatahandler.InitDatalist;
57 var
58 dHandle: THandle;
59 pData: PFileData;
60 numRecords, i: Integer;
61 begin
62 pData := nil;
63 dHandle := FindResource(hInstance, '
64 if dHandle <> 0 then65 begin66 numRecord := SizeofResource(hInstance, dHandle) div Sizeof(TFiledata);
67 FResHandle := LoadResource(hInstance, dHandle);
68 if FResHandle <> 0 then69 begin70 pData := LockResource(dHandle);
71 if pData <> nilthen72 begin73 FData.Capacity := NumRecords;
74 for i := 1 to Numrecords do75 begin76 FData.Add(pData);
77 Inc(pData);
78 end;
79 end80 else81 raise Exception.Create('Lock failed');
82 end83 else84 raise Exception.Create('Load failed');
85 end86 else87 raise Exception.Create('Resource not found');
88 end;
You can add a method to sort the FData list, for example, or a filter method that would populate another TList with pointer to records that match a set of criteria.