I want to create a method that reads a directory and finds and saves in a data structure all the directories included, as well as all the sub-directories of each directory. Specifically I want the names to be cited as:
folder1
folder11
folder12
folder2
folder21
folder22
folder23
I need obviously a function with recursion.
I use temporary a class member method in a console application as:
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");
}
Ok, I know not the best written code, but I want initially to have a view of the names caught. However it does not work properly, since it considers the name of the parent directory more than once. Even if I put the invocation of the same method out (not performing recursion) the first two names are . and .. . Why?
Could you suggest me a function doing the described process or indicate the correction demanded on this function?
as some comment pointed out, boost::filesystem is the usually way to go.
But from your code it seems you are still a newbie to C++, so I’ve rewritten in C++ idiomatic way, adding a bit of useful display. HTH
note that in your code, storing
struct dirent *ep;in class is plain wrong, because you overwrite it while recursing…