使用C++在目录中进行文件计数

har*_*rik 12 c++

如何使用C++标准库获取目录中的文件总数?任何帮助表示赞赏.

Luk*_*keN 14

如果不排除基本上始终可用的C标准库,则可以使用该标准库.因为无论如何它都可以使用,与boost不同,它是一个非常实用的选项!

这里给出一个例子.

和这里:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main (void)
{
  DIR *dp;
  int i = 0;
  struct dirent *ep;     
  dp = opendir ("./");

  if (dp != NULL)
  {
    while (ep = readdir (dp))
      i++;

    (void) closedir (dp);
  }
  else
    perror ("Couldn't open the directory");

  printf("There's %d files in the current directory.\n", i);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

果然

 > $ ls -a | wc -l
138
 > $ ./count
There's 138 files in the current directory.
Run Code Online (Sandbox Code Playgroud)

这根本不是C++,但它可以在大多数(如果不是全部)操作系统上使用,并且无论如何都可以在C++中使用.

更新:我将更正我之前关于这是C标准库的一部分的陈述 - 事实并非如此.但是你可以将这个概念带到其他操作系统,因为它们都有自己处理文件的方式,而不必占用额外的库.

  • 这是一个愚蠢的投票.当然,您可以使用C标准库计算文件.以我在帖子中包含的示例 - 而不是在用于迭代每个文件的while中调用"puts ...",只需执行"i ++"并在上面的某处声明"int i".当然没有"directory_get_file_count"函数,但这不是重点.关键是,您可以使用它来获得所需的结果,即文件夹中的文件数量.地狱,让我用勺子喂答案编辑我原来的答案,秒 (7认同)
  • @LukeN:POSIX**是**"特殊库支持".Windows没有`<sys/types.h>`也没有`<dirent.h>`.POSIX不是C标准库,你断言它是错误的. (3认同)

Yac*_*oby 10

你不能.你能得到的最接近的是使用像Boost.Filesystem这样的东西

  • 之后它是微不足道的:`int count = std :: difference(directory_iterator(dir_path),directory_iterator());` (6认同)
  • @MSalters,我找不到任何对`std :: difference`的引用.你确定你不是指'std :: distance`吗?此外,你需要一个`static_cast <int>`来强制`directory_iterator :: difference_type`到`int`. (4认同)

小智 6

一个老问题,但由于它首先出现在谷歌搜索上,我想添加我的答案,因为我需要类似的东西.

int findNumberOfFilesInDirectory(std::string& path)
{
    int counter = 0;
    WIN32_FIND_DATA ffd;
    HANDLE hFind = INVALID_HANDLE_VALUE;

    // Start iterating over the files in the path directory.
    hFind = ::FindFirstFileA (path.c_str(), &ffd);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do // Managed to locate and create an handle to that folder.
        { 
            counter++;
        } while (::FindNextFile(hFind, &ffd) == TRUE);
        ::FindClose(hFind);
    } else {
        printf("Failed to find path: %s", path.c_str());
    }

    return counter;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

从 C++17 开始,它可以用 STL 来完成:

auto dirIter = std::filesystem::directory_iterator("directory_path");

int fileCount = std::count_if(
    begin(dirIter),
    end(dirIter),
    [](auto& entry) { return entry.is_regular_file(); }
);
Run Code Online (Sandbox Code Playgroud)

一个简单的 for 循环也有效:

auto dirIter = std::filesystem::directory_iterator("directory_path");
int fileCount = 0;

for (auto& entry : dirIter)
{
    if (entry.is_regular_file())
    {
        ++fileCount;
    }
}

Run Code Online (Sandbox Code Playgroud)

请参阅https://en.cppreference.com/w/cpp/filesystem/directory_iterator