Delete, insert, sort 6.2.7 Records
The basic idea for deleting a record is to get the location of the current record and move the record forward one after the other. The file was truncated before the last record.
For i:=currentrec+1 to Count-1 do
Begin
Seek (Methodfile,i);
Read (METHODFILE,METHODREC);
Seek (methodfile,i-1);
Write (METHODFILE,METHODREC);
End
Truncate (Methodfile);
To avoid accidental deletion, a message box is displayed before the delete operation to confirm. To update the values and display content of global variables after deletion:
Count: = Count-1;
Changegrid;
The complete procedure is as follows:
Procedure Trecfileform.deletebuttonclick (Sender:tobject);
Var
Newfile:methodfiletype;
Methodrec:tmethod;
newfilename:string;
I:integer;
Begin
If fileopened = False then Exit;
Currentrec: = stringgrid1.row-1;
If Currentrec < 0 then Exit;
If Messagedlg (' Delete current record? ', Mtconfirmation,
[Mbyes, mbno], 0 = Idyes Then
Begin
Hazattr.text: = ';
For I: = currentrec+1 to Count-1 do
Begin
Seek (Methodfile,i);
Read (METHODFILE,METHODREC);
Seek (methodfile,i-1);
Write (METHODFILE,METHODREC);
End
Truncate (Methodfile);
Count: = Count-1;
Changegrid;
End
End
The delete operation shown here is straightforward. But when the program began to design I took a detour, and later found that although this method used to record the deletion of the operation appears clumsy, ridiculous, but it is precisely the idea of record insertion, sorting.
The core of this idea is to create a new file to save the updated content. If the new file is successfully created, delete the original file, or restore the original file. The list of procedures is as follows:
Procedure Trecfileform.deletebuttonclick (Sender:tobject);
Var
Newfile:methodfiletype;
Methodrec:tmethod;
newfilename:string;
I:integer;
Begin
If fileopened = False then Exit;
Currentrec: = stringgrid1.row-1;
If Currentrec < 0 then Exit;
If Messagedlg (' Delete current record? ', Mtconfirmation,
[Mbyes, mbno], 0 = Idyes Then
Begin
Hazattr.text: = ';
NewFileName: = Changefileext (FileName, '. Sav ');
Try
AssignFile (Newfile,filename);
ReWrite (NewFile);
Except
On Einouterror do
Begin
Rename (Methodfile,filename);
Exit;
End
End
For I: = 1 to Count do
If I <> currentrec+1 Then
Begin
Methodrec: = Gridtorec (i);
Write (NEWFILE,METHODREC);
End
CloseFile (Methodfile);
Try
AssignFile (Methodfile,filename);
Reset (Methodfile);
Except
On Einouterror do
Begin
DeleteFile (FileName);
AssignFile (Methodfile,newfilename);
Reset (Methodfile);
Rename (Methodfile,filename);
Exit;
End
DeleteFile (NewFileName);
count:=count-1;
Changegrid;
End
End
The method is basically the same for record insertion. For sorting, you can first read the key fields into the sort, and then rewrite the files in the order of the record numbers corresponding to the sort results.