[fpc-pascal] Adding file to string to the RTL

Ryan Joseph genericptr at gmail.com
Wed Oct 7 02:53:51 CEST 2020


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.


Regards,
	Ryan Joseph



More information about the fpc-pascal mailing list