# CodeGuru Technical FAQs > CodeGuru Individual FAQs >  Windows SDK File System: How to count files within a directory and subdirectories?

## Andreas Masur

*Q:* How to count files within a directory and subdirectories?

*A:*



```
#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;
}
```

----------

