【问题标题】:count number of files with a given extension in a directory - C++?计算目录中具有给定扩展名的文件数 - C++?
【发布时间】:2010-12-28 11:05:05
【问题描述】:

是否可以在 C++ 中计算目录中具有给定扩展名的文件的数量?

我正在编写一个程序,它会很好地做这样的事情(伪代码):

if (file_extension == ".foo")
    num_files++;
for (int i = 0; i < num_files; i++)
    // do something

显然,这个程序要复杂得多,但这应该让您大致了解我正在尝试做什么。

如果这不可能,请告诉我。

谢谢!

【问题讨论】:

    标签: c++ file-io directory file-extension


    【解决方案1】:

    这种功能是特定于操作系统的,因此没有标准的可移植方法。

    但是,使用 Boost's Filesystem library 您可以做到这一点,并以可移植的方式执行更多与文件系统相关的操作。

    【讨论】:

      【解决方案2】:

      C 或 C++标准 本身没有关于目录处理的任何内容,但几乎任何值得其盐的操作系统都会有这样的野兽,一个例子是 findfirst/findnext 函数或 readdir

      您的方法是对这些函数进行简单循环,检查返回的字符串的结尾是否为您想要的扩展。

      类似:

      char *fspec = findfirst("/tmp");
      while (fspec != NULL) {
          int len = strlen (fspec);
          if (len >= 4) {
              if (strcmp (".foo", fspec + len - 4) == 0) {
                  printf ("%s\n", fspec);
              }
          }
          fspec = findnext();
      }
      

      如上所述,您将用于遍历目录的实际函数是特定于操作系统的。

      对于 UNIX,几乎可以肯定会使用 opendirreaddirclosedir。这段代码是一个很好的起点:

      #include <dirent.h>
      
      int len;
      struct dirent *pDirent;
      DIR *pDir;
      
      pDir = opendir("/tmp");
      if (pDir != NULL) {
          while ((pDirent = readdir(pDir)) != NULL) {
              len = strlen (pDirent->d_name);
              if (len >= 4) {
                  if (strcmp (".foo", &(pDirent->d_name[len - 4])) == 0) {
                      printf ("%s\n", pDirent->d_name);
                  }
              }
          }
          closedir (pDir);
      }
      

      【讨论】:

      • 在上述两种情况下。 for(;;) 循环会不会更整洁?
      • 我认为是品味或风格问题,@Martin。我倾向于将 for 循环用于简单的事情(主要是“for i = 1 到 10”排序),而将 while 用于更复杂的循环。但无论哪种情况,都与手头的问题无关。
      【解决方案3】:

      首先,您要为什么操作系统编写代码?

      • 如果是 Windows,则在 MSDN 中查找 FindFirstFileFindNextFile
      • 如果您正在寻找 POSIX 系统的代码,请阅读 man 以获得 opendirreaddirreaddir_r
      • 对于跨平台,我建议使用 Boost.Filesystem 库。

      【讨论】:

        猜你喜欢
        • 2017-05-09
        • 2021-02-14
        • 2010-11-22
        • 2012-04-02
        • 2019-05-21
        • 1970-01-01
        • 2011-01-24
        • 1970-01-01
        • 2016-01-28
        相关资源
        最近更新 更多