How to get the number of files in the specific folder using C or C++ function? [duplicate]

StackOverflow https://stackoverflow.com/questions/12075864

  •  27-06-2021
  •  | 
  •  

Question

Possible Duplicate:
count number of files with a given extension in a directory - C++?

How to get the number of files in the specific folder using c or c++ function? Is there any c library function that could get the number of files in a given directory?

Was it helpful?

Solution

Here is a working example of opendir/readdir/closedir use (no recursion here):

void listdir(char *dir) {
  struct dirent *dp;
  DIR *fd;

  if ((fd = opendir(dir)) == NULL) {
    fprintf(stderr, "listdir: can't open %s\n", dir);
    return;
  }
  while ((dp = readdir(fd)) != NULL) {
  if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
    continue;    /* skip self and parent */
  printf("%s/%s\n", dir, dp->d_name);
  }
  closedir(fd);
}

OTHER TIPS

I don't think there is any standard method of listing the files in a directory. I remember when I had to do this before, I ended up using Boost Filesystem.

With boost::filesystem it could look like this:

#include <iostream>
#include <algorithm>
#include <iterator>
#include <boost/filesystem.hpp>
#include <boost/iterator/filter_iterator.hpp>
namespace fs = boost::filesystem;

int main()
{
    fs::path p("D:/mingw/include");
    fs::directory_iterator dir_first(p), dir_last;

    auto pred = [](const fs::directory_entry& p)
    {
        return fs::is_regular_file(p);
    };

    std::cout <<
        std::distance(boost::make_filter_iterator(pred, dir_first, dir_last),
                      boost::make_filter_iterator(pred, dir_last, dir_last));
}

You need to open the directory with opendir(), and loop through the whole directory using readdir()... and count how many times you do.

Remember that '.' and '..' are special entries and don't count.

If you need to count files only and no directories, you will have to check explicitly in the dir struct (man stat).

If you need to have the number of files in the folder and its subfolders, then you will have to recurse ("walk") inside the directories - and maybe, depending on the platform, checking for symlinks.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top