Counting files

How can i count files of a given type in a directory.
 
eg. how many *.txt files in c:\temp ?

LVL 1
pr_wainwrightAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Fatman121898Connect With a Mentor Commented:
Hi pr_wainwright,
you may also use component Listbox (Tab Win3.1).
Just put it on your form, set Drive and Directory properties to given drive and directory, set Mask property to '*.txt' and read property Items.Count. Here is some simple code that I have just written to illustrate this.

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, FileCtrl;

type
  TForm1 = class(TForm)
    FileListBox1: TFileListBox;
    Label1: TLabel;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
  FileListBox1.Drive:='C';
  FileListBox1.Directory:='\windows';
  FileListBox1.Mask:='*.txt';
  Label1.Caption:=IntToStr(FileListBox1.Items.Count);
end;

end.

Hope it helps,
Jo.
0
 
kretzschmarCommented:
hi pr_wainwright,

try something like this

var
  SRec : TSearchRec;
  Count : Integer;
begin
  Count := 0;
  if FindFirst('C:\Temp\*.txt'),faAnyFile,Srec) = 0 then
  Repeat
    inc(Count;
  Until FindNext(Srec) <> 0;
  FindClose(Srec);
  Showmessage(Inttostr(Count)+' files found');
end;

just from head, therefore there could be typos

meikl ;-)
0
 
kretzschmarCommented:
hi again,

here the tested version
(stripped of typos)

procedure TForm1.Button1Click(Sender: TObject);
var
  SRec : TSearchRec;
  Count : Integer;
begin
  Count := 0;
  if FindFirst('C:\Temp\*.txt',faAnyFile,Srec) = 0 then
  Repeat
    inc(Count);
  Until FindNext(Srec) <> 0;
  FindClose(Srec);
  Showmessage(Inttostr(Count)+' files found');
end;

meikl
0
 
Fatman121898Commented:
Oops, for Temp directory the statement should be:
....
FileListBox1.Directory:='\temp';
....
I mean my code, not meikl's.

:-)
Jo.
0
All Courses

From novice to tech pro — start learning today.