Mega Code Archive

 
Categories / Delphi / Files
 

Find the number of files or the oldest file matching a file spec

Title: Find the number of files or the oldest file matching a file spec Question: How do I count the number of files matching c:\temp\*.dat? What is the oldest file matching c:\windows\*rep.*? Answer: {This unit contains a form with: a Button an EditBox If you type into the edit box a string such as c:\windows\*.dll, then click on the button - a message box will appear that shows text like this: The oldest file matching c:\windows\*.dll is c:\windows\somefile.dll } unit oldestfileu; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Edit1: TEdit; Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; function FileCount(FileSpec: string): longint; function GetOldestFile(FileSpec: string): string; implementation {$R *.DFM} {This function can be used to return the name of the oldest file which matches the FileSpec} function GetOldestFile(FileSpec: string): string; var SR: TSearchRec; DosError: integer; Oldest: string; OldestDTime: TDateTime; begin {if there is more than one file that matches FileSpec then find the one with the oldest date} if FileCount(FileSpec)1 then begin DosError := FindFirst(FileSpec, faAnyFile-faDirectory, SR); if DosError=0 then begin Oldest := ExtractFilePath(FileSpec)+SR.Name; OldestDTime := FileDateToDateTime(SR.Time); while FindNext(SR)=0 do begin if FileDateToDateTime(SR.Time) begin Oldest := ExtractFilePath(FileSpec)+SR.Name; OldestDTime := FileDateToDateTime(SR.Time); end; end; Result := Oldest; end; end else {if there is only one file then return its name} begin DosError := FindFirst(FileSpec, faAnyFile, SR); if DosError=0 then begin Result := ExtractFilePath(FileSpec)+SR.Name; end else {if there are no matching files then return blank} Result := ''; end; end; {This function can be used to return the number of files in a directory which match the FileSpec} function FileCount(FileSpec: string): longint; var SR: TSearchRec; DosError: integer; c: longint; begin c := 0; DosError := FindFirst(FileSpec, faAnyFile, SR); if DosError=0 then begin if (SR.Name'.') and (SR.Name'..') then inc(c); while FindNext(SR)=0 do begin if (SR.Name'.') and (SR.Name'..') then inc(c); end; end else c := 0; FileCount := c; end; procedure TForm1.Button1Click(Sender: TObject); begin ShowMessage('The oldest file matching '+Edit1.Text +' is: '+GetOldestFile(Edit1.Text)); end; end.