寻找帮助以io.h递归扫描目录

时间:2014-08-08 04:54:04

标签: c++ recursion directory

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

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作为学习递归写函数的方法;我不打算使用提升或其他任何东西。当我扫描路径并找到文件时,它会将扩展名推送到地图。如果文件是目录,它将再次调用该函数并打印出结果。

我不确定从哪里开始,我正在寻求一般的帮助,不一定是答案,但指出了我正确的方向,我会自己弄明白!

1 个答案:

答案 0 :(得分: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);
}
相关问题