-
October 2nd, 2004, 02:00 PM
#1
Windows SDK File System: How to count files within a directory and subdirectories?
Q: How to count files within a directory and subdirectories?
A:
Code:
#include <string>
#include <iostream>
#include <windows.h>
#include <conio.h>
int CountFiles(const std::string &refcstrRootDirectory,
const std::string &refcstrExtension,
bool bSubdirectories = true)
{
int iCount = 0;
std::string strFilePath; // Filepath
std::string strPattern; // Pattern
std::string strExtension; // Extension
HANDLE hFile; // Handle to file
WIN32_FIND_DATA FileInformation; // File information
strPattern = refcstrRootDirectory + "\\*.*";
hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
if(hFile != INVALID_HANDLE_VALUE)
{
do
{
if(FileInformation.cFileName[0] != '.')
{
strFilePath.erase();
strFilePath = refcstrRootDirectory +
"\\" +
FileInformation.cFileName;
if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if(bSubdirectories)
{
// Search subdirectory
int iRC = CountFiles(strFilePath,
refcstrExtension,
bSubdirectories);
if(iRC != -1)
iCount += iRC;
else
return -1;
}
}
else
{
// Check extension
strExtension = FileInformation.cFileName;
strExtension = strExtension.substr(strExtension.rfind(".") + 1);
if((refcstrExtension == "*") ||
(strExtension == refcstrExtension))
{
// Increase counter
++iCount;
}
}
}
} while(::FindNextFile(hFile, &FileInformation) == TRUE);
// Close handle
::FindClose(hFile);
}
return iCount;
}
int main()
{
int iNumberOfFiles = 0;
// Count all files in 'c:' and its subdirectories
iNumberOfFiles = CountFiles("c:", "*");
if(iNumberOfFiles == -1)
{
std::cout << "Error " << std::endl;
return -1;
}
// Print results
std::cout << "Number of files = " << iNumberOfFiles << std::endl;
// Count '.avi' files in 'c:'
iNumberOfFiles = CountFiles("c:", "avi", false);
if(iNumberOfFiles == -1)
{
std::cout << "Error " << std::endl;
return -1;
}
// Print results
std::cout << "Number of files = " << iNumberOfFiles << std::endl;
// Wait for keystroke
_getch();
return 0;
}
Last edited by Andreas Masur; July 24th, 2005 at 05:14 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|