【问题标题】:C++ folder opening and file countingC++ 文件夹打开和文件计数
【发布时间】:2016-01-29 00:00:03
【问题描述】:

所以这是我的代码,但我不能阻止它打印出来:. ..并将它们视为一个文件。我不明白为什么。 输出是:

.
1files.
..
2files.
course3.txt
3files.
course2.txt
4files.
course1.txt
5files.

但是只有 3 个文件...应该说 3 个文件而不是 . ..我不知道它的意思。

int folderO(){
    DIR *dir;
    struct dirent *ent;
    int nFiles=0;
    if ((dir = opendir ("sampleFolder")) != NULL) {
      /* print all the files and directories within directory */
      while ((ent = readdir (dir)) != NULL) {
        std::cout << ent->d_name << std::endl;
        nFiles++;
        std::cout << nFiles << "files." << std::endl;
      }
      closedir (dir);
    } 
    else {
      /* could not open directory */
      perror ("");
      return EXIT_FAILURE;
    }
}

【问题讨论】:

  • 我可以按照我想要的方式实现吗?
  • 我在这里没有看到任何代码可以过滤掉...,所以我不明白你对它们的出现感到惊讶。

标签: c++ file count directory


【解决方案1】:

。和 .. 分别是元目录、当前目录和父目录。

您发现子目录与文件一起打印。符号链接和其他“奇怪”的 Unix-y 东西也是如此。如果您不想打印它们,有几种方法可以过滤掉它们:

如果您的系统支持dirent 结构中的d_type,请在打印前检查d_type == DT_FILE。 (GNU page on dirent listing possible d_types)

if (ent->d_type == DT_FILE)
{
    std::cout << ent->d_name << std::endl;
    nFiles++;
    std::cout << nFiles << "files." << std::endl;
}

如果不支持d_type,则stat the file name and check that it is a file st_mode == S_ISREG

struct stat statresult;
if (stat(ent->d_name, &statresult) == 0)
{
    if (statresult.st_mode == S_ISREG)
    {
        std::cout << ent->d_name << std::endl;
        nFiles++;
        std::cout << nFiles << "files." << std::endl;
    }
}

当然还有基于 strcmp 的简单的 if 语句,但这会列出所有其他子目录。

废话。对不起。 C++。最后一行应该是“当然还有基于愚蠢的std::stringoperator== 的 if 语句,但这将列出所有其他子目录。”

【讨论】:

    【解决方案2】:

    Google 搜索会发现这些是具有以下含义的特殊文件夹名称:

    • .当前目录
    • ..父目录

    任何有关迭代目录的教程都向您展示了如何使用简单的“if”语句将它们过滤掉。

    【讨论】:

      【解决方案3】:

      . 是当前目录 inode(技术上是硬链接),.. 是父目录。

      这些用于导航。它们是目录,如果它们是目录,也许你可以忽略它们?

      【讨论】:

      • 我可以按照我想要的方式实现吗?我必须摆脱那些,或者我只需要找到 .txt 文件。这怎么可能?
      • @hfakar 你可以strcmp(ent-&gt;d_name, ".") 跳过它。
      • @hfakar:也许是if 声明?
      猜你喜欢
      • 1970-01-01
      • 2011-05-21
      • 2019-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 2012-09-21
      相关资源
      最近更新 更多