我们先来看一下需求.
我们需要查找某一个目录下面,体积最大的 exe 文件。
可以用下面的函数:
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;
这里用到了两个函数:
function FindFirst(const Path: string; Attr: Integer; var F: TSearchRec): Integer;
其中有一句:FindFirst returns 0 if a file was successfully located
也就是说,当成功找到文件时,返回0.
function FindNext(var F: TSearchRec): Integer;
FindNext 则是寻找下一个
TSearchRec 是一个文件信息的纪录,当FindFirst返回SearchRec时,你可以通过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;