在C++中通过递归查找目录和子目录

Find directories and sub-directories through recursion in C++

本文关键字:子目录 查找 递归 C++      更新时间:2023-10-16

我想创建一个方法,该方法读取目录并在数据结构中查找并保存包含的所有目录以及每个目录的所有子目录。具体来说,我希望这些名字被引用为:

文件夹1 文件夹11 文件夹12文件夹2 文件夹21 文件夹22 文件夹23

我显然需要一个带有递归的函数。我在控制台应用程序中使用临时类成员方法,如下所示:

private:
 struct dirent *ep;

void DirectoryReader::parseDirectory(char* readingDirectory)
{
char* tempDirectory = (char*)malloc(sizeof(readingDirectory) + 200); 
string temp = readingDirectory;
DIR *dp;
dp = opendir (readingDirectory);
   if (dp != NULL)
     {
       while (ep = readdir (dp))
       {
         puts (ep->d_name);
         temp += readingDirectory;
         temp += "/";
         temp += ep->d_name;
         char * buffer = new char[temp.length()];
         strcpy(buffer,temp.c_str());
         parseDirectory(buffer);
       }
         (void) closedir (dp);
     }
   else
     perror ("Couldn't open the directory");

}

好的,我知道不是最好的代码,但我想首先查看捕获的名称。但是,它不能正常工作,因为它会多次考虑父目录的名称。即使我放弃了对相同方法的调用(不执行递归),前两个名称也是 .和。。.为什么?

您能否向我推荐一个执行所述过程的函数或指出对该函数要求的更正?

正如一些评论指出的那样,boost::filesystem是通常要走的路。但是从你的代码来看,你似乎仍然是C++新手,所以我以C++习惯的方式重写,添加了一些有用的显示。呵呵

#include <dirent.h>
#include <iostream>
#include <string>
using namespace std;
struct DirectoryReader
{
    static void parseDirectory(string readingDirectory, int level);
};
void DirectoryReader::parseDirectory(string readingDirectory, int level)
{
    if (DIR *dp = opendir(readingDirectory.c_str()))
    {
        cout << string(level, ' ') << readingDirectory << endl;
        while (struct dirent *ep = readdir(dp))
            if (ep->d_type == DT_DIR && ep->d_name[0] != '.')
                parseDirectory(readingDirectory + "/" + ep->d_name, level + 1);
        closedir(dp);
    }
    else
        cerr << "Couldn't open the directory " << readingDirectory << endl;
}
int main_parsedir(int argc, char **argv)
{
    if (argc > 1)
        DirectoryReader::parseDirectory(argv[1], 0);
    return 0;
}

请注意,在您的代码中,将struct dirent *ep;存储在类中是完全错误的,因为您在递归时覆盖了它......

目录枚举函数通常返回当前目录 (.) 和父目录 (..) 链接。你需要忽略它们。此外,您需要检查 ep->d_type。我为您编写了以下函数。请检查这是否按预期工作。我没有使用空格分隔符进行输出,因为各个文件夹中可以包含空格字符。另外,我不确定您将如何使用此输出,因为它会丢失树结构。

#include "dirent.h"
const string theDelimiter = "\";
class DirectoryReader
{
public:
    string DirectoryReader::parseDirectory(string readingDirectory, const string& aCurrentFolderName)
    {
        string aChildren;
        aChildren += theDelimiter;
        aChildren += aCurrentFolderName;
        DIR *dp = opendir (readingDirectory.c_str());
        if (dp != NULL)
        {
            struct dirent *ep = NULL;
            while ((ep = readdir (dp)) && ep->d_type == DT_DIR )
            {
                string aDirName = ep->d_name;
                //  Ignore current directory and the parent directory links
                if(!aDirName.compare(".") || !aDirName.compare(".."))
                    continue;
                //  Form the full directory path
                string aFullFolderName = readingDirectory;
                aFullFolderName += string("\");
                aFullFolderName += aDirName;
                string aChildrenFolders = parseDirectory(aFullFolderName, aDirName);
                if(aChildrenFolders.compare(""))
                {
                    aChildren += aChildrenFolders;
                }
            }
            (void) closedir (dp);
        }
        else
            perror ("Couldn't open the directory");
        return aChildren;
    }
};