[fpc-pascal] Adding file to string to the RTL
Ryan Joseph
genericptr at gmail.com
Wed Oct 7 17:17:02 CEST 2020
Here's another interesting option I considered. You can call Scandir which returns a record with an enumerator. You can then use this to drop right into the for loop. It doesn't allocate memory and you can break the loop to stop the iteration. The benefit is you can avoid costly memory allocations for large directories but I don't think it's a replacement for a function that returns an array of TStringList.
type
TDirectoryEnumerator = record
path: string;
count: integer;
name: string;
info: TSearchRec;
function GetEnumerator: TDirectoryEnumerator;
function MoveNext: boolean;
property Current: string read name;
end;
function TDirectoryEnumerator.GetEnumerator: TDirectoryEnumerator;
begin
result := self;
end;
Function TDirectoryEnumerator.MoveNext: Boolean;
begin
if count = 0 then
begin
if FindFirst(path, faAnyFile, info) = 0 then
begin
name := info.name;
inc(count);
result := true;
end
else
result := false;
end
else if FindNext(info) <> 0 then
begin
FindClose(info);
result := false;
end
else
begin
name := info.name;
inc(count);
result := true;
end;
end;
function ScanDir(path: string): TDirectoryEnumerator;
begin
if not DirectoryExists(path) then
raise Exception.Create('Directory "'+path+'"" doesn''t exist');
result.path := path+DirectorySeparator+'*';
result.count := 0;
end;
Regards,
Ryan Joseph
More information about the fpc-pascal
mailing list