Jellery
Jellery

Reputation: 55

Looking for help recursively scanning directory with io.h

Hi I'm trying to write a function that will recursively search a path and child directories and push the extension of each file into a map as the key and have the value count the number of file types. Here is what I have so far, I was able to create a function to that displayed info about all the files/folders in the path entered, however I'm having trouble recursively scanning the directory. This is what I'm working with...

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;
}

I've yet to comment it so I'll try to explain it:

I'm using io.h as a means of learning how to recursively write a function; I am not going to use boost or anything else. When I scan the path and find a file, it will push the extension to a map. If the file is a directory, it will call the function again and print out the results.

I'm not sure where to go from here and am looking for general help, not necessarily the answer but point me in the right direction and I'll figure it out myself!

Upvotes: 0

Views: 364

Answers (1)

Andy Brown
Andy Brown

Reputation: 12999

This...

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

should be this...

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

Upvotes: 1

Related Questions