Help & Manual authoring tool
Using FindFirst, FindNext, and FindClose to get the files in a directory (folder)

Looking for files

Copyright © 2000 Ernesto De Spirito

LMD-Tools 6.1 - 300+ components for various development tasks!

FindFirst, FindNext, FindClose

To search for files matching a certain filename specification (like 'C:\WINDOWS\*.INI') we use the FindFirst and FindNext functions and the FindClose procedure. For them to work, we need a TSearchRec record that among other things will contain information of a file matching the search criteria. We use a code like the following:

uses SysUtils;

procedure TForm1.Button1Click(Sender: TObject);
var
  SearchRec: TSearchRec;
begin
  if FindFirst('C:\WINDOWS\*.INI', faAnyFile and not
     (faVolumeID or faDirectory), SearchRec) = 0 then
  begin
    repeat
      // Here we process each fond file.
      // Its info is in SearchRec.
    until FindNext(SearchRec) <> 0;
    FindClose(SearchRec);
  end;
end;

If FindFirst returns 0, it means it found at least one file matching the specified criteria. Then we use FindNext to retrieve the info of the next files that match the criteria one by one. FindNext also returns 0 if it finds a file. After we processed all files, we should close the search calling FindClose that releases some resources in SearchRec that were allocated by FindFirst.

If attributes is 0, FindFirst and then FindNext will only find normal files, meaning that files marked as Archive, Read-only, Hidden, System, Directory or Volume will be excluded from the search. To include those files in the search, add (Or) their corresponding constants: faArchive, faReadOnly, faHidden, faSysFile, faDirectory and faVolumeID.

If you want to search for files in a directory and all its subdirectories you can use this example.

TSearchRec

This structure (record) contains the information of a file found by file FindFirst and FindNext. The most important field is Name (a string), which contains the long name of the found file, without the path.

type
TSearchRec = record
  Time: Integer;
  Size: Integer;
  Attr: Integer;
  Name: TFileName;
  ExcludeAttr: Integer;
  FindHandle: THandle;
  FindData: TWin32FindData; // Additional information
end;

The Time field is a DOS date-and-time stamp and represents the date of the last modification made to the file. You can convert this value to a TDateTime type using FileDateToDateTime.

JfControls Library - for Delphi and C++ Builder
Copyright © 2000/2006 Ernesto De Spirito.   All rights reserved.