Helpful Information
 
 
Category: Delphi Programming
Counting number of files in a directory

Hi people. Probably a simple thing. I need to count the number of files in a directory and then output that to a text file. I can do the text file part. Not sure about the counting the files. Please help.

You can use FindFirst, FindNext and FindClose to iterate through a directory. You can count the files while iterating thru the dir. See the example for FindFirst in the help file for how to use these functions.

I have looked at the helpfiles and it isnt very clear. The example is checking file attributes. Please will you give me abit more details. Thanks

The following code evaluates all the files in C:\*.* and excludes directories from that file count.


function TForm1.CountFiles : integer;
var
Rec : TSearchRec;
nFileCount : integer;
foo : string;
begin
nFileCount := 0;
if FindFirst('C:\*.*', faAnyFile, Rec) = 0 then
begin
repeat
// Exclude directories from the list of files.
if ((Rec.Attr and faDirectory) <> faDirectory) then
Inc(nFileCount);
until FindNext(Rec) <> 0;
FindClose(Rec);
end;
Result := nFileCount;
end;










privacy (GDPR)