So, basically I'm having an assignment, but that isn't the actual problem. The assignment requires me to use a list, which is fine so far.
So the idea is the following: I'm having a function which prints the contents of a directory recursively, which works fine, but now I'm trying to get each entry saved in a queue, which I'm later gonna use for something else. The nasty part is that I push each entry (the d_name from the dirent structure) into the queue in that function, and if I print the contents of the queue directly at the end of the function, it returns fine, but if I print the results in main, I get also garbage.
So my test directories look like this:
-DummyDir
-DummyDir2
-DummyDir6
-DummyDir7
-DummyDir3
-DummyDir8
-DummyDir4
-DummyDir9
-DummyDir10
-DummyDir5
-DummyDir11
-DummyDir12
My function looks like this:
void dirwrap(char* dir, std::queue<char*>* queue)
{
DIR* dirOpen;
if(!(dirOpen = opendir(dir))){
printf("Couldn't open directory: %s\n", dir);
exit(-1);
}
struct dirent* dd;
char path[2000];
while ((dd = readdir(dirOpen)) != NULL)
{
if (strcmp(dd->d_name, ".") != 0 && strcmp(dd->d_name, "..") != 0) {
//printf("%s\n", dd->d_name);
queue->push(dd->d_name);
sprintf(path, dir, "%s", sizeof(dir));
strcat(path, "/");
strcat(path, dd->d_name);
dirwrap(path, queue);
}
}
closedir(dirOpen);
}
And if I print the contents of queue right after closedir I get a good result, like this:
DummyDir2
DummyDir6
DummyDir7
DummyDir5
DummyDir12
DummyDir11
DummyDir3
DummyDir8
DummyDir4
DummyDir9
DummyDir10
But if I print the contents of my queue in main, I get this:
DummyDir2
DummyDir9
DummyDir10
DummyDir5
8�)�W▒
.
DummyDir3
~n��w▒
DummyDir4
DummyDir9
DummyDir10
I really can't seem to understand why is actually doing this, so I would really appreciate it if you would help me.
std::string's?dd->d_namewhatever the way, see my answer