Forum > General
Scanning over files, directories and sub-directories
(1/1)
Jishaxe:
I have a rather novice question, but I can't really find any good tutorials on Google to work it out.
I would like to iliterate over files, directories and the directories' sub-directories. So basicly a full system scan.
I attempted this, but failed. (Not giving an exception for some reason)
--- Code: ---procedure scanfiles(filename,direct: String)
begin
SetCurrentDir(direct);
if FindFirst(filename,faDirectory,rec) = 0 then
begin
repeat
scanfiles(filename,rec.Name);
until FindNext(rec) <> 0;
end;
if FindFirst(filename,faAnyFile,rec) = 0 then
begin
repeat
Form1.Memo1.Lines.Add('Found file: '+CRLF+rec.Name);
until FindNext(rec) <>0;
end;
end;
--- End code ---
Can anyone help me, please?
JuhaManninen:
First param to FindFirst is a path, not filename. SetCurrentDir has no effect for it.
This is one function I have made (originally for Delphi). Maybe there are similar ones in LCL libs, don't know. It shows the idea anyway.
--- Code: ---type
// Must return True on success.
FindFileCallBack = function(FileName: string): Boolean;
...
function FindFile(Dir: string; Func: FindFileCallBack): Boolean;
// Finds every file in a given directory and its sub-directories recursively
// and calls Func using the file name as parameter.
// Parameters : Dir -- Directory with the files to find.
// Returns True on success.
var
F: TSearchRec;
begin
Result := True;
Dir := AppendPathDelim(Dir);
try
if FindFirst(Dir + '*.*', faAnyFile, F) = 0 then
repeat
if (F.Attr and faDirectory > 0) then // Directories
begin
if (F.Name<>'.') and (F.Name<>'..') then // Not '.' and '..'
Result := FindFile(Dir + F.Name, Func); // Recursive call.
end
else // Single file
Result := Func(Dir + F.Name);
if not Result then
Exit;
until FindNext(F) <> 0;
finally
SysUtils.FindClose(F);
end;
end;
--- End code ---
If you also want to filter the files with a wildcard mask, do something like this:
--- Code: --- if FindFirst(Dir + Mask, faAnyFile, F) = 0 then
--- End code ---
Juha
Jishaxe:
Thank you for your help :)
theo:
There's also TFileSearcher:
http://lazarus-ccr.sourceforge.net/docs/lcl/fileutil/tfilesearcher.html
Navigation
[0] Message Index