Page 1 of 1

dynamic Arrays: read from file (Delphi)

Posted: Fri Jan 17, 2003 12:58 am
by Schubi
This pieces of code are for a keyboard testing software.
to test any keyboard, you have to know, what and how many keycodes every key produces.
so this program should wait for every single key of the keyboard an write ist into a file.
for this i have defined the following types:


type
TKeyCode = record //A single keypress produces 1 to 4 codes,
//every single one will be saved in a TKeyCode
Scn : Integer; //Scancode
Code : Integer; //virtual Keycode
end;

//dynamic Array
//reason: dont know how many TKeycodes will be needed for a single keypress
type TCodes = Array of TKeyCode;

type
TKey = record
Count : Integer; //Count of TKeycode in The Array below
Codes : TCodes; //Array[1..Count] of TKeyCode
end;

So TKey defines all codes a keypress (and release) will produce


KeyArray : Array[1..128] of TKey;

The keyboards have up to 128 keys. so i define a Array of TKey

This Array will be filled by my program, but not every
keyboard have 128 keys, so the Array wont be full.
to make reading in file easyer i write a Integer with the size of the following TKey
in front of every TKey: SizeOf(Key)

here the procedure that writes the array in a file

var
Key : TKey;
Size : Integer;
Number : Integer;
begin
AssignFile(Protokoll,'C:\Test.dat');
Rewrite(Protokoll);
ForNumber := 1 to 128 do begin
Key:=KeyArray[Number];
Size := SizeOf(Key);
BlockWrite(Protokoll,Size,SizeOf(Size));
Blockwrite(Protokoll,Taste,SizeOf(Key));
end;
CloseFile(Protokoll);
end;


now the testing software have to read this file and write the data back into the Array of TKey

var
Number : Integer;
Protokoll : File;
read : Integer;
Size : Integer;
Key : TKey;
high : Integer;
begin
try
AssignFile(Protokoll,'C:\Test.Dat');
Reset(Protokoll);
except
MessageDlg('Error opening File!',mtError, [mbOK], 0);
end;
For Number := 1 to 128 do begin
Blockread(Protokoll,Size,4,read);//read a Integer
If Read = 4 Then begin
BlockRead(Protokoll,Key,Size,read);//read a TKey
//set the new size of the Array (necessary?????)
SetLength(KeyArray[Number].Codes,SizeOf(Key.Codes));
KeyArray[Number]:= Key;
end;
end;
CloseFile(Protokoll);
end;


This procedure produces an exception in cause of the size of the array or something
in one of these lines:

SetLength(KeyArray[Number].Codes,SizeOf(Key.Codes));
KeyArray[Number]:= Key;


whats wrong with this?
even you know a better way to save and read the array,
even other types

and excuse my bad english :-)

Greats, Schubi