I am trying to list all the directories in a given directory. I have this code:
var
srec: TSearchRec;
begin
// folder is some absolute path of a folder
if FindFirst(folder + PathDelim + '*', faDirectory, srec) = 0 then
try
repeat
if (srec.Name <> '.') and (srec.Name <> '..') then
ShowMessage(srec.Name);
until FindNext(srec) <> 0;
finally
FindClose(srec);
end;
But for some reason I get messages about file names instead of directories only. I thought that using faDirectory
would make FindFirst
and family only return names of directories. What am I doing wrong? If I change it to
if FindFirst(folder, faDirectory, srec) = 0 then
Then it only shows the name of folder
but not as an absolute path (relative to folder + '/..'
) and quits afterwards.
I realise that I can check if it is a directory by making sure that (srec.Attr and faDirectory) = faDirectory
but I feel like that's doing things in a roundabout way and there should be a proper way of doing it.
If you are using delphi xe, check the TDirectory.GetDirectories
function.
The SysUtils.FindFirst
Documentation has the answer to your issue.
function FindFirst(const Path: string; Attr: Integer; var F: TSearchRec): Integer;
The Attr parameter specifies the special files to include in addition to all normal files. Choose from these file attribute constants when specifying the Attr parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With