Page 1 of 1
Forum

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



Share:
Notifications
Clear all

[Solved] Lazarus Pascal - Is a directory empty?

2 Posts
1 Users
0 Reactions
4,801 Views
 Hans
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2948
Topic starter  

For one of my projects, I needed to determine if a directory was empty, and I couldn't find a function for this.
So I wrote a tiny procedure that does this for us, and it should cover Windows, Linux and MacOS:

function isEmptyDirectory(aDir:string):boolean;
var
SearchRecResult: TSearchRec;
begin
Result := FindFirst(IncludeTrailingPathDelimiter(aDir) + '*', faAnyFile, SearchRecResult)<>0;

while (SearchRecResult.Name = '.') or (SearchRecResult.Name = '..') do
Result := FindNext(SearchRecResult) <> 0;;

FindClose(SearchRecResult);
end;

   
ReplyQuote
 Hans
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2948
Topic starter  

The previous function checks if a directory is completely empty, meaning: it has files and/or directories in it.

Sometimes you don't care if there are any empty subdirectories, so the following variant tests if there are any files in the directory or its subdirectories. So it will only look for files! Empty directories are ignored, and subdirectories are recursed through to find at least one file.

I made it generic, so we can toggle this on and off.

Set checkForFilesOnly to true to only look for files.
Set it to false to look for any files or directories (like the previous version).

function isEmptyDirectory(aDir:string; checkForFilesOnlys:boolean = false):boolean;
var
  SearchRecResult: TSearchRec;
  FoundAFile: boolean;
begin
  FoundAFile := FindFirst(IncludeTrailingPathDelimiter(aDir) + '*', faAnyFile, SearchRecResult) = 0;

  while FoundAFile and
        ( DirectoryExists(IncludeTrailingPathDelimiter(aDir)+SearchRecResult.Name) and
          ( (SearchRecResult.Name='.') or
            (SearchRecResult.Name='..') or
            (checkForFilesOnlys and isEmptyDirectory(IncludeTrailingPathDelimiter(aDir)+SearchRecResult.Name)) ) ) do
      FoundAFile := FindNext(SearchRecResult) = 0;

  FindClose(SearchRecResult);
  Result := not(FoundAFile);
end;  

 


   
ReplyQuote
Share: