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

淺唱寂寞╮ 提交于 2019-12-01 09:37:31

There is nothing in the C or C++ standards themselves about directory handling but just about any OS worth its salt will have such a beast, one example being the findfirst/findnext functions or readdir.

The way you would do it is a simple loop over those functions, checking the end of the strings returned for the extension you want.

Something like:

char *fspec = findfirst("/tmp");
while (fspec != NULL) {
    int len = strlen (fspec);
    if (len >= 4) {
        if (strcmp (".foo", fspec + len - 4) == 0) {
            printf ("%s\n", fspec);
        }
    }
    fspec = findnext();
}

As stated, the actual functions you will use for traversing the directory are OS-specific.

For UNIX, it would almost certainly be the use of opendir, readdir and closedir. This code is a good starting point for that:

#include <dirent.h>

int len;
struct dirent *pDirent;
DIR *pDir;

pDir = opendir("/tmp");
if (pDir != NULL) {
    while ((pDirent = readdir(pDir)) != NULL) {
        len = strlen (pDirent->d_name);
        if (len >= 4) {
            if (strcmp (".foo", &(pDirent->d_name[len - 4])) == 0) {
                printf ("%s\n", pDirent->d_name);
            }
        }
    }
    closedir (pDir);
}

This kind of functionality is OS-specific, therefore there is no standard, portable method of doing this.

However, using Boost's Filesystem library you can do this, and much more file system related operations in a portable manner.

First of all what OS are you writing for?

  • If it is Windows then look for FindFirstFile and FindNextFile in MSDN.
  • If you are looking the code for POSIX systems, read man for opendir and readdir or readdir_r.
  • For cross platform I'd suggest using Boost.Filesystem library.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!