Code: Alles auswählen
function TStringFile.Create(S:ShortString):Integer;
begin
... FileStream.WriteBuffer(S,SizeOf(S));
end;
function TIntegerFile.Create(I:Integer):Integer;
begin
... FileStream.WriteBuffer(I,SizeOf(I));
end;
Ich habe also mal folgendes kleine Testprojekt begonnen:
Code: Alles auswählen
generic FileAccessor<T> = class
private
FCurrentRecord: Integer;
FFileName: string;
procedure SetCurrentRecord(AValue: Integer);
procedure SetFileName(AValue: string);
public
function Create(Value: T): integer; overload; // append to file
function Create(): integer; overload; // append empty record to file
function Read(var Value: T): boolean; // read from file
function Write(Value: T; Idx: integer): boolean; // write to file
function Delete(Idx: integer): boolean; // delete from file (flag as overwritable)
function toStr(Idx:Integer):String; // return content as hex dump for debugging
property FileName: string read FFileName write SetFileName; // Name of the data file
property CurrentRecord : Integer read FCurrentRecord write SetCurrentRecord; // pointer to the record last accessed
function Count:Integer; // return number of records in file
constructor Create(AFileName:String); //
end;
...
procedure FileAccessor.SetCurrentRecord(AValue: Integer);
begin
if FCurrentRecord=AValue then Exit;
if AValue > Self.Count - 1 then exit;
if AValue < -1 then exit;
FCurrentRecord:=AValue;
end;
...
function FileAccessor.Create(Value: T): integer;
// Append a record, return the record index
var
FileStream: TFileStream;
begin
if FileExists(FileName) then
FileStream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite)
else
FileStream := TFileStream.Create(FileName, fmCreate or fmShareDenyWrite);
FileStream.Seek(0,soEnd);
FileStream.WriteBuffer(Value,SizeOf(T));
FreeAndNil(FileStream);
result := Self.Count - 1;
end;
Code: Alles auswählen
type
TIntegerFile = specialize FileAccessor<Integer>;
TStringFile = specialize FileAccessor<ShortString>;
var
Form1: TForm1;
IntegerFileAccessor: TIntegerFile;
StringFileAccessor: TStringFile;
CurrentAccessor: .... was nu?
Code: Alles auswählen
procedure TForm1.ButtonNextClick(Sender: TObject);
begin
if Assigned(CurrentAccessor) then
begin
CurrentAccessor.CurrentRecord := CurrentAccessor.CurrentRecord + 1;
StatusBar1.SimpleText := Format('%s: %d', [CurrentAccessor.FileName, CurrentAccessor.CurrentRecord]);
end;
end;
Richtig oder falsch?
HG, Armin.