To access files and file information, you can generally rely on the standard functions available in the SysUtils unit. Relying on these fairly traditional Pascal libraries makes your code easily portable among quite different operating systems (although you'll have to consider with great care the differences in the file system architectures, particularly case sensitivity on the Linux platform).
For example, the FilesList example uses the FindFirst, FindNext, and FindClose combination to retrieve from within a folder a list of files that match a filter, with the same code you could use on Kylix and Linux (an example of the output appears in Figure 3.5).
The following code adds the filenames to a list box called lbFiles:
procedure TForm1.AddFilesToList(Filter, Folder: string; Recurse: Boolean); var sr: TSearchRec; begin if FindFirst (Folder + Filter, faAnyFile, sr) = 0 then repeat lbFiles.Items.Add (Folder + sr.Name); until FindNext(sr) <> 0; FindClose(sr);
If the Recurse parameter is set, the AddFilesToList procedure gets a list of subfolders by examining the local files again, and then calls itself for each of the subfolders. The list of folders is placed in a string list object, with the following code:
procedure GetSubDirs (Folder: string; sList: TStringList); var sr: TSearchRec; begin if FindFirst (Folder + '*.*', faDirectory, sr) = 0 then try repeat if (sr.Attr and faDirectory) = faDirectory then sList.Add (sr.Name); until FindNext(sr) <> 0; finally FindClose(sr); end; end;
Finally, the program uses an interesting technique to ask the user to select the initial directory for the file search, by calling the SelectDirectory procedure (see Figure 3.6):
if SelectDirectory ('Choose Folder', '', CurrentDir) then ...