Description
This example shows how to used the Win 32 API functions
FindFirstFile(), FindNextFile() and FindFile(), to count
CountFiles.cpp
Copyright © 1997-2002 Rodolfo A. Frino. All rights reserved.
a) The number of subdirectories, and
b) The total number of files
under the specified directory
Form1 contains a button.
#include <vcl.h>
#pragma hdrstop
#include "CountFiles.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
struct DirFileCount
{
int DirCount;
int FileCount;
};
void Count_Files(String Path, DirFileCount* p)
{
if ( Path[Path.Length()] != '\\' )
Path += String("\\");
String mask = ( Path + "*.*" );
WIN32_FIND_DATA fd = {0};
HANDLE h = FindFirstFile( mask.c_str(), &fd ); //Win 32 API
if( h != INVALID_HANDLE_VALUE )
{
while( FindNextFile( h, &fd ) ) //Win 32 API
{
String File = fd.cFileName;
if( File == "." || File == ".." )
continue;
if( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
//FILE ATTRIBUTE IS A DIRECTORY:
Count_Files(Path + File, p);
p->DirCount++;
}
else
{
//FILE ATTRIBUTTE IS NOT A DIRECTORY:
p->FileCount++;
}
}
FindClose( h ); //Win 32 API
}
else
{
ShowMessage("Error: FindFirstFile() returned an Invalid Handle");
}
}
//------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
struct DirFileCount o;
struct DirFileCount* p = &o;
p->DirCount = 0;
p->FileCount = 0;
//Specify your directory here
//
Count_Files("C:\\TEST", p);
ShowMessage("Dir =" + String(p->DirCount)
+ " File =" + String(p->FileCount));
}