type
Tperson = Packed Record
name:string[20];
Mi:String[2];
end;
PersonFile=File of TPerson;
var
PF
ersonFile;
function FindRecord(Name:String):Integer;
var // return -1 if failed
i:Integer;
Person:TPerson;
begin
Result:=-1;
for i:=0 to FileSize(PF)-1 do
begin
Seek(PF,i);
Read(PF,Person);
if Person.name=Name then
begin
Result:=i;
exit;
end;
end;
end;
function InsertRecord(Loc:Integer;Person:TPerson):Boolean;
var //Loc=0 -> add before head Loc=FileSize -> add after tail
i:Integer;
P:TPerson;
begin
Result:=false;
if (Loc>FileSize(PF)) or (Loc<0) then
exit;
for i:=FileSize(PF)-1 downto Loc do
begin
Seek(PF,i);
Read(PF,P);
Seek(PF,i+1);
Write(PF,P);
end;
Seek(PF,Loc);
Write(PF,Person);
Result:=true;
end;
function DeleteRecord(Loc:Integer):Boolean;
var // Loc = 0..FileSize-1
i:Integer;
Person:TPerson;
begin
Result:=false;
if (Loc>=FileSize(PF)) or (Loc<0) then
exit;
for i:=Loc+1 to FileSize(PF)-1 do
begin
Seek(PF,i);
Read(PF,Person);
Seek(PF,i-1);
Write(PF,Person);
end;
Truncate(PF);
Result:=true;
end;
procedure TForm1.Button8Click(Sender: TObject);
var
Person:TPerson;
i:Integer;
begin
AssignFile(PF,'Person.txt');
Rewrite(PF);
for i:=1 to 100 do
begin
Person.name:='Mike '+IntToStr(i);
Person.Mi:=IntToStr(i mod 2);
Write(PF,Person);
end;
Person.name:='Add Name';
Person.Mi:='A';
InsertRecord(FindRecord('Mike 1'),Person);
Person.Mi:='B';
InsertRecord(FindRecord('Mike 25'),Person);
DeleteRecord(FindRecord('Mike 90'));
FillChar(Person.name,12,0);
Person.name:='HaHa!';
Person.Mi:='**';
InsertRecord(FileSize(PF),Person);
CloseFile(PF);
end;
OK!