Author: William Gerbert
Find files with FindFirst and FindNext
Answer:
The procedure FindFiles locates files (by a given "filemask") and adds their
complete path to a stringlist. Note that recursion is used: FindFiles calls itself
at the end of the procedure!
Before calling FindFiles, the stringlist has to be created; afterwards, you must
free the stringlist.
In StartDir you pass the starting directory, including the disk drive. In FileMask
you pass the name of the file to find, or a file mask. Examples:
1 FindFiles('c:\', 'letter01.doc')
2 FindFiles('d:\', 'euroen??.dpr')
3 FindFiles('d:\projects', '*.dpr')
If you want to test this procedure, start a new project and add some components to
the form: two Edits (one for the starting directory, one for the mask), a Button, a
TLabel and a ListBox.
4 implementation
5 ....
6 var
7 FilesList: TStringList;
8 ...
9
10 procedure FindFiles(StartDir, FileMask: string);
11 var
12 SR: TSearchRec;
13 DirList: TStringList;
14 IsFound: Boolean;
15 i: integer;
16 begin
17 if StartDir[length(StartDir)] <> '\' then
18 StartDir := StartDir + '\';
19
20 { Build a list of the files in directory StartDir
21 (not the directories!) }
22
23 IsFound :=
24 FindFirst(StartDir + FileMask, faAnyFile - faDirectory, SR) = 0;
25 while IsFound do
26 begin
27 FilesList.Add(StartDir + SR.Name);
28 IsFound := FindNext(SR) = 0;
29 end;
30 FindClose(SR);
31
32 // Build a list of subdirectories
33 DirList := TStringList.Create;
34 IsFound := FindFirst(StartDir + '*.*', faAnyFile, SR) = 0;
35 while IsFound do
36 begin
37 if ((SR.Attr and faDirectory) <> 0) and
38 (SR.Name[1] <> '.') then
39 DirList.Add(StartDir + SR.Name);
40 IsFound := FindNext(SR) = 0;
41 end;
42 FindClose(SR);
43
44 // Scan the list of subdirectories
45 for i := 0 to DirList.Count - 1 do
46 FindFiles(DirList[i], FileMask);
47
48 DirList.Free;
49 end;
50
51 procedure TForm1.ButtonFindClick(Sender: TObject);
52 begin
53 FilesList := TStringList.Create;
54 FindFiles(EditStartDir.Text, EditFileMask.Text);
55 ListBox1.Items.Assign(FilesList);
56 LabelCount.Caption := 'Files found: ' + IntToStr(FilesList.Count);
57 FilesList.Free;
58 end;
|