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 - Find All Files in a directory and subdirectories matching criteria

2 Posts
1 Users
0 Likes
8,789 Views
 Hans
(@hans)
Famed Member Admin
Joined: 11 years ago
Posts: 2660
Topic starter  

With the usual TSearchRec and FindFirst functions (also found in Delphi) one can retrieve all files in a directory and subdirectories.

To my pleasant surprise, Lazarus has a great little function in the "fileutil" unit called FindAllFiles() which does all this for you and shoves the result nicely in a TStringList ... 

uses 
...
fileutil
...
var
PascalFiles: TStringList;
begin
//No need to create the stringlist; the function does that for you
PascalFiles := FindAllFiles(LazarusDirectory, '*.pas;*.pp;*.p;*.inc', true); //find e.g. all pascal sourcefiles
try
showmessage(Format('Found %d Pascal source files',[PascalFiles.Count]));
finally
PascalFiles.Free;
end;

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

Note: 

FindAllFiles also allows the use of a rather poorly documented parameter "DirAttr".
With this parameter you can determine what kind of "files" will be returned.

Constant        Value   Description       Linux Meaning
faReadOnly 1 Read-only files Current user does not have write access. 
faHidden 2 Hidden files File name begins with ".". 
faSysFile 4 System files File is socket, symbolic link, device file, or FIFO. 
faVolumeID 8 Volume ID files Not used. 
faDirectory 16 Directory files Directory. 
faArchive 32 Archive files Not used. 
faSymLink 64 Symbolic link File is a symbolic link. 
faAnyFile 71 Any file Any file. 

So if you want only directories, set this value to faDirectory (or 16).
If you want everything but directories, set this to 182 (1+2+4+8+32+64+71).

p.s. there is also a FindAllDirectories functions, which would have been just as easy of course. But the DirAttr can be used for other purposes as well, for example for listing on hidden files, etc.


   
ReplyQuote

Like what you see and you'd like to help out? 

The best way to help is of course by assisting others with their questions here in the forum, but you can also help us out in other ways:

- Do your shopping at Amazon, it will not cost you anything extra but may generate a small commission for us,
- send a cup of coffee through PayPal ($5, $10, $20, or custom amount),
- become a Patreon,
- donate BitCoin (BTC), or BitCoinCash (BCH).

Share: