Pascal · lekcja 27 z 30 · Narzędzia dla NAS-aPrzejdź przez foldery
FindFirst i FindNext czytają folder, a procedura wywołuje samą siebie dla każdego podfolderu.
27-largest-files.pas Pobierz 27-largest-files.pas
program LargestFiles;
{$mode objfpc}{$H+}
uses
SysUtils, Classes;
{ TStringList sortuje jak tekst, więc rozmiar stoi na początku, z zerami z przodu }
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('użycie: 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Ćwiczenie
Przyjmij liczbę wierszy jako argument.