NASutils Knowledge BaseUnofficialPolski

Pascal · lesson 27 of 30 · Tools for the NASWalk through folders

FindFirst and FindNext read a folder, and the procedure calls itself for each subfolder.

Programming on the NAS › Pascal in 30 lessons

27-largest-files.pas Download 27-largest-files.pas

program LargestFiles;
{$mode objfpc}{$H+}
uses
  SysUtils, Classes;

{ TStringList sorts by text, so the size goes first with leading zeros }
procedure Collect(const Folder: string; List: TStrings);
var
  Found: TSearchRec;
begin
  if FindFirst(Folder + '/*', faAnyFile or faSymLink, Found) = 0 then
  try
    repeat
      if (Found.Name = '.') or (Found.Name = '..') or ((Found.Attr and faSymLink) <> 0) then
        Continue;
      if (Found.Attr and faDirectory) <> 0 then
        Collect(Folder + '/' + Found.Name, List)
      else
        List.Add(Format('%.15d %s/%s', [Found.Size, Folder, Found.Name]));
    until FindNext(Found) <> 0;
  finally
    FindClose(Found);
  end;
end;

var
  List: TStringList;
  I: Integer;
begin
  if not DirectoryExists(ParamStr(1)) then
  begin
    WriteLn('usage: 27-largest-files FOLDER');
    Halt(2);
  end;
  List := TStringList.Create;
  try
    Collect(ParamStr(1), List);
    List.Sort;
    for I := List.Count - 1 downto List.Count - 3 do
      if I >= 0 then
        WriteLn(StrToInt64(Copy(List[I], 1, 15)):8, '  ', Copy(List[I], 17, MaxInt));
  finally
    List.Free;
  end;
end.

Terminal

$ ./27-largest-files photos
   15800  photos/wedding.mov
    7300  photos/trip.mp4
    4200  photos/beach.jpg

Exercise

Take the number of rows as an argument.