[fpc-pascal] Adding file to string to the RTL
Michael Van Canneyt
michael at freepascal.org
Wed Oct 7 10:19:50 CEST 2020
On Tue, 6 Oct 2020, Ryan Joseph via fpc-pascal wrote:
> Since we're on the topic how about another one-liner for reading all the files in directory into a dynamic array? This has the added benefit of getting enumeration for free. This is standard stuff for working with files in scripting languages so I think the FPC RTL should include something like this also.
>
> ================================
>
> type
> TStringArray = array of string;
>
> function FindAllFiles(path: string): TStringArray;
> var
> info: TSearchRec;
> begin
> if not DirectoryExists(path) then
> raise Exception.Create('Directory "'+path+'"" doesn''t exist');
> path := path+DirectorySeparator+'*';
> result := [];
> if FindFirst(path, faAnyFile, info) = 0 then
> begin
> repeat
> result += [info.name];
> until FindNext(info) <> 0;
> FindClose(info);
> end;
> end;
>
> begin
> // fastest way to read all text files in a directory.
> // only 2 lines doesn't leak memory
> for name in FindAllFiles('/usr/local/lib/fpc') do
> writeln(GetFileAsString('/usr/local/lib/fpc/'+name));
> end.
I see Delphi has something similar, so I will add an implementation.
But I need to study the options they provide so we can make a reasonably
compatible version :)
Michael.
More information about the fpc-pascal
mailing list