计算文件夹C++窗口中的目录数
count the number of directories in a folder C++ windows
我编写了一个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;
}
相关文章:
- 如何将更多文件夹添加到c++include路径
- GetShortPathName在网络驱动器上使用中文文件夹时失败
- VS2017,C++包含目录与附加包含目录,子文件夹包含失败-但为什么
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何在文档文件夹中创建目录
- "assimp/config.h"找不到,但它在文件夹中
- C++入门 5 版:类消息和文件夹
- 我可以在 Arduino 的库文件夹之外安装库吗?
- 如何按文件扩展名引用文件夹中的文件
- 在QTreeView中仅显示共享驱动器和文件夹
- 加载与引用 .NET DLL 位于同一文件夹中的引用的 .NET DLL 时"Not found"异常
- 介子复制/安装头文件到输出目录并保持文件夹结构
- vcruntime.h 从 Windows 包含文件夹中丢失?
- 在文件夹迭代上实现 RAII
- 使用 Powershell 命令将 cpp 文件的文件夹编译为 GNU 的 g++
- 使文件夹中的所有文件可供所有项目(子目录)访问
- 无法使用 CMake 从其他文件夹添加源文件
- 如何在安卓工作室中将c ++头文件从一个文件夹导入到另一个文件夹?
- 如何从Windows控制台调用.exe(C++)以在不同的目录(或任何目录)中创建文件夹?
- 如何识别项目是 QT 中的文件还是文件夹