Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File count in a directory using C++

Tags:

c++

How do I get the total number of files in a directory by using C++ standard library?

like image 701
harik Avatar asked May 10 '10 11:05

harik


3 Answers

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

like image 75
Yacoby Avatar answered Oct 09 '22 02:10

Yacoby


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

like image 21
LukeN Avatar answered Oct 09 '22 03:10

LukeN


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;
}
like image 5
Tal T Avatar answered Oct 09 '22 03:10

Tal T