计算文件夹C++窗口中的目录数

count the number of directories in a folder C++ windows

本文关键字:文件夹 C++ 窗口 计算      更新时间:2023-10-16

我编写了一个Java程序,该程序可以计算目录中文件夹的数量。我想把这个程序翻译成C++(我正在努力学习)。我已经能够翻译大部分程序,但我还没能找到一种计算目录子目录的方法。我该如何做到这一点?

提前感谢

下面是一个使用Win32 API的实现。

SubdirCount采用目录路径字符串参数,并返回其直接子目录的计数(作为int)。隐藏的子目录包括在内,但不包括任何名为"."或".."的子目录。

FindFirstFile是一个TCHAR别名,最终为FindFirstFileA或FindFirstFileW。为了保持字符串TCHAR,而不假设CString的可用性,这里的示例包括一些笨拙的代码,只是为了在函数的参数后面附加"/*"。

#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('');
// 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;
}