【问题标题】:Looking for help recursively scanning directory with io.h使用 io.h 递归扫描目录寻求帮助
【发布时间】:2014-10-01 12:10:46
【问题描述】:

您好,我正在尝试编写一个函数,该函数将递归搜索路径和子目录,并将每个文件的扩展名作为键推送到映射中,并让值计算文件类型的数量。这是我到目前为止所拥有的,我能够创建一个函数来显示有关输入路径中所有文件/文件夹的显示信息,但是我在递归扫描目录时遇到了麻烦。这就是我正在使用的......

std::string FileExtractor(const std::string input)
{
    std::string::size_type idx;
    idx = input.rfind('.');

    if (idx != std::string::npos)
    {
        return input.substr(idx + 1);
    }
    else
    {
        return "none";
    }
}
std::map<std::string, int> recursive(std::string path)
{
    intptr_t hFile;
    struct _finddata_t fd;
    std::string filespec = "*.*";
    std::string findPath = path + filespec;
    hFile = _findfirst(findPath.c_str(), &fd);
    std::map<std::string, int> myMap;
    std::string size = "";

    if (hFile == -1L)
    {
        std::cout << "No  " << filespec << " files in the current dir\n";
    }
    else
    {
        std::cout << "Scanning recursively in " << path << "\n" << std::endl;
        do
        {
            if ((fd.name != std::string(".")) && (fd.name != std::string("..")))
            {
                std::cout << fd.name;
                ++myMap[FileExtractor(fd.name)];
                if (fd.attrib & _A_SUBDIR)
                {
                    std::string str = path + fd.name + "\\";
                    recursive(path);
                }
            }
        } while (_findnext(hFile, &fd) == 0);

        _findclose(hFile);  // close the file handle
    }
    return myMap;
}

我还没有评论它,所以我会尝试解释它:

我使用 io.h 作为学习如何递归编写函数的方法;我不会使用 boost 或其他任何东西。当我扫描路径并找到一个文件时,它会将扩展名推送到地图上。如果文件是目录,它将再次调用该函数并打印出结果。

我不确定从这里去哪里,我正在寻找一般帮助,不一定是答案,但指出我正确的方向,我会自己解决!

【问题讨论】:

  • not necessarily the answer 好吧,因为您还没有提出问题,所以很难给出答案。该代码以何种方式无法完成您希望它执行的操作?
  • 现在这是一个永远不会退出的无限循环。我试图让它在扫描完目录中的每个文件(包括所有子目录)后退出
  • 我不明白为什么它不会退出。我没有看到代码有任何明显的问题(除了你煞费苦心地构建地图,然后返回它,然后调用者立即忽略返回值)。输出是什么样的?它是否取得了进展,还是一遍又一遍地打印相同的文件名?也许它需要的时间比你预期的要长。

标签: c++ recursion directory


【解决方案1】:

这...

if (fd.attrib & _A_SUBDIR)
{
    std::string str = path + fd.name + "\\";
    recursive(path);
}

应该是这个……

if (fd.attrib & _A_SUBDIR)
{
    std::string str = path + fd.name + "\\";
    recursive(str);
}

【讨论】:

  • ...您可能应该在打印中添加 EOL:std::cout &lt;&lt; fd.name &lt;&lt; std::endl;
猜你喜欢
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-05
  • 2021-06-16
  • 1970-01-01
  • 2014-09-30
  • 1970-01-01
相关资源
最近更新 更多