File count in a directory using C++

As of C++17 it can be done with STL:

auto dirIter = std::filesystem::directory_iterator("directory_path");

int fileCount = std::count_if(
    begin(dirIter),
    end(dirIter),
    [](auto& entry) { return entry.is_regular_file(); }
);

A simple for-loop works, too:

auto dirIter = std::filesystem::directory_iterator("directory_path");
int fileCount = 0;

for (auto& entry : dirIter)
{
    if (entry.is_regular_file())
    {
        ++fileCount;
    }
}

See https://en.cppreference.com/w/cpp/filesystem/directory_iterator


You can't. The closest you are going to be able to get is to use something like Boost.Filesystem

EDIT: It is possible with C++17 using the STL's filesystem library


An old question, but since it appears first on Google search, I thought to add my answer since I had a need for something like that.

int findNumberOfFilesInDirectory(std::string& path)
{
    int counter = 0;
    WIN32_FIND_DATA ffd;
    HANDLE hFind = INVALID_HANDLE_VALUE;

    // Start iterating over the files in the path directory.
    hFind = ::FindFirstFileA (path.c_str(), &ffd);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do // Managed to locate and create an handle to that folder.
        { 
            counter++;
        } while (::FindNextFile(hFind, &ffd) == TRUE);
        ::FindClose(hFind);
    } else {
        printf("Failed to find path: %s", path.c_str());
    }

    return counter;
}

If you don't exclude the basically always available C standard library, you can use that one. Because it's available everywhere anyways, unlike boost, it's a pretty usable option!

An example is given here.

And here:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (void)
{
  DIR *dp;
  int i = 0;
  struct dirent *ep;     
  dp = opendir ("./");

  if (dp != NULL)
  {
    while (ep = readdir (dp))
      i++;

    (void) closedir (dp);
  }
  else
    perror ("Couldn't open the directory");

  printf("There's %d files in the current directory.\n", i);

  return 0;
}

And sure enough

 > $ ls -a | wc -l
138
 > $ ./count
There's 138 files in the current directory.

This isn't C++ at all, but it is available on most, if not all, operating systems, and will work in C++ regardless.

UPDATE: I'll correct my previous statement about this being part of the C standard library - it's not. But you can carry this concept to other operating systems, because they all have their ways of dealing with files without having to grab out additional libraries.

EDIT: : Added initialization of i

Tags:

C++