【问题标题】:count the number of directories in a folder C++ windows计算文件夹中的目录数 C++ windows
【发布时间】:2014-01-31 18:04:21
【问题描述】:

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

提前致谢

【问题讨论】:

  • 到目前为止你有什么代码来获取目录?你在 Java 中做了什么,你在 C++ 中尝试了什么?
  • 你应该寻找诸如opendirreaddir之类的函数。如果要查找目录条目的信息(例如是否为子目录),则需要使用fstat
  • FindFirstFileFindNextFile 或(最好)Boost Filesystem,它有一个目录迭代器,您可以将其与标准算法一起使用。
  • @JerryCoffin 你能举个例子吗?我是 C++ 新手。

标签: c++ directory subdirectory


【解决方案1】:

这是一个使用 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('\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;
}

【讨论】:

    猜你喜欢
    • 2015-06-28
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    相关资源
    最近更新 更多