2009. május 23., szombat

How to sort directory entries by date / time


Problem/Question/Abstract:

How to sort directory entries by date / time

Answer:

type
  PEntryItem = ^TEntryItem;
  TEntryItem = record
    FName: string;
    FDate: TDateTime;
    FSize: Integer;
  end;

function SortList(item1, item2: Pointer): integer;
var
  i1: PEntryItem absolute Item1;
  i2: PEntryItem absolute Item2;
begin
  if (i1^.fdate > i2^.fdate) then
    result := 1 {greater}
  else if (i1^.fdate < i2^.fdate) then
    result := -1 {smaller}
  else
    result := 0; {equals}
end;

procedure DoTheJob;
var
  List: TList;
  i: Integer;

  procedure GetDirEntries(Path: string);
  var
    Dta: TSearchRec;
    P: PEntryItem;
  begin
    if (Path <> '') and (Path[Length(Path)] = '\') then
      setlength(Path, Pred(Length(Path)));
    if FindFirst(Path + '\*.*', faAnyFile, Dta) <> 0 then
      exit; {Nothing}
    repeat
      {remove next line if you want these two as well}
      if (Dta.Name = '.') or (dta.name = '..') then
        continue;
      New(P);
      P^.FName := Dta.Name;
      P^.FSize := Dta.Size;
      P^.FDate := FileDateToDateTime(Dta.Time);
      List.Add(P);
    until
      (FindNext(Dta) <> 0);
    FindClose(Dta);
  end;

begin
  List := TList.Create;
  List.Clear;
  try
    GetDirEntries('C:\Windows');
    if (list.Count > 0) then
      List.Sort(SortList);
    {Now you have a list with all the files in the directory
                        sorted by its date/time field. To access them do as follows:}
    for i := 0 to list.count - 1 do
    begin
      with PEntryItem(List.Items[i])^ do
      begin
        {I assume you have a Form called MainFrm with a Listbox1}
        MainFrm.ListBox1.Items.Add(Format('%s  %d  %s', [FName, FSize,
          FormatDateTime('dd/mm/yyyy HH:NN:SS', FDate)]));
      end;
    end;
  finally
    {make sure to relase the memory allocated}
    while (list.count > 0) do
    begin
      Dispose(PEntryItem(List.Items[0]));
      List.Delete(0);
    end;
    List.Free;
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése