我們先來看一下需求.
我們需要查找某一個(gè)目錄下面,體積最大的 exe 文件。
可以用下面的函數(shù):
K:=FindFirst(AppRootPath+'\*.exe',faAnyFile, vSearchRec);
while K = 0 do
begin
if (AppRootFileName <> vSearchRec.Name) and (i< vSearchRec.Size) then
begin
i:=vSearchRec.Size;
AppName:= vSearchRec.Name;
end;
K:= FindNext(vSearchRec);
end;
這里用到了兩個(gè)函數(shù):
function FindFirst(const Path: string; Attr: Integer; var F: TSearchRec): Integer;
其中有一句:FindFirst returns 0 if a file was successfully located
也就是說,當(dāng)成功找到文件時(shí),返回0.
function FindNext(var F: TSearchRec): Integer;
FindNext 則是尋找下一個(gè)
TSearchRec 是一個(gè)文件信息的紀(jì)錄,當(dāng)FindFirst返回SearchRec時(shí),你可以通過SearchRec.Name獲取文件名,以及 SearchRec.Size獲取文件大小等信息。
The following example uses an edit control, a button, a string grid, and seven check boxes. The check boxes correspond to the seven possible file attributes. When the button is clicked, the path specified in the edit control is searched for files matching the checked file attributes. The names and sizes of the matching files are inserted into the string grid.
procedure TForm1.Button1Click(Sender: TObject);
var
sr: TSearchRec;
FileAttrs: Integer;
begin
StringGrid1.RowCount := 1;
if CheckBox1.Checked then
FileAttrs := faReadOnly
else
FileAttrs := 0;
if CheckBox2.Checked then
FileAttrs := FileAttrs + faHidden;
if CheckBox3.Checked then
FileAttrs := FileAttrs + faSysFile;
if CheckBox4.Checked then
FileAttrs := FileAttrs + faVolumeID;
if CheckBox5.Checked then
FileAttrs := FileAttrs + faDirectory;
if CheckBox6.Checked then
FileAttrs := FileAttrs + faArchive;
if CheckBox7.Checked then
FileAttrs := FileAttrs + faAnyFile;
with StringGrid1 do
begin
RowCount := 0;
if FindFirst(Edit1.Text, FileAttrs, sr) = 0 then
begin
repeat
if (sr.Attr and FileAttrs) = sr.Attr then
begin
RowCount := RowCount + 1;
Cells[1,RowCount-1] := sr.Name;
Cells[2,RowCount-1] := IntToStr(sr.Size);
end;
until FindNext(sr) <> 0;
FindClose(sr);
end;
end;
end;