Question

I have written a Java program that at one point counts the number of folders in a directory. I would like to translate this program into C++ (I'm trying to learn it). I've been able to translate most of the program, but I haven't been able to find a way to count the subdirectories of a directory. How would I accomplish this?

Thanks in advance

Was it helpful?

Solution

Here is an implementation using the Win32 API.

SubdirCount takes a directory path string argument and it returns a count of its immediate child subdirectories (as an int). Hidden subdirectories are included, but any named "." or ".." are not counted.

FindFirstFile is a TCHAR-taking alias which ends up as either FindFirstFileA or FindFirstFileW. In order to keep strings TCHAR, without assuming availabilty of CString, the example here includes some awkward code just for appending "/*" to the function's argument.

#include <tchar.h>
#include <windows.h>

int SubdirCount(const TCHAR* parent_path) {
    // The hideous string manipulation code below
    // prepares a TCHAR wildcard string (sub_wild)
    // matching any subdirectory immediately under 
    // parent_path by appending "\*"
    size_t len = _tcslen(parent_path);
    const size_t alloc_len = len + 3;
    TCHAR* sub_wild  = new TCHAR[alloc_len];
    _tcscpy_s(sub_wild, alloc_len, parent_path);
    if(len && sub_wild[len-1] != _T('\\')) { sub_wild[len++] = _T('\\'); }
    sub_wild[len++] = _T('*');
    sub_wild[len++] = _T('\0');

    // File enumeration starts here
    WIN32_FIND_DATA fd;
    HANDLE hfind;
    int count = 0;
    if(INVALID_HANDLE_VALUE  != (hfind = FindFirstFile(sub_wild, &fd))) {
        do {
            if(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                // is_alias_dir is true if directory name is "." or ".."
                const bool is_alias_dir = fd.cFileName[0] == _T('.') && 
                    (!fd.cFileName[1] || (fd.cFileName[1] == _T('.') &&
                    !fd.cFileName[2]));

                count += !is_alias_dir;
            }
        } while(FindNextFile(hfind, &fd));
        FindClose(hfind);
    }

    delete [] sub_wild;
    return count;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top