I’ve been trying to write an iterative dir in c. I began with a standard recursive directory traversal, which works as expected. Now I’m trying to convert this into an iterative version using a queue structure, but it’s behaving unexpectedly. Somehow a file in the sub-directory is getting added to my queue, and the program obviously fails when trying to open a file as a directory.
Code Snippet
char *dirName;
DIR *dp;
struct dirent *d_ent;
struct stat s;
char name[80];
...
while(!IsEmpty(q)){
dirName = FrontAndDequeue(q);
if((dp = opendir(dirName)) == NULL) {
printf("ERROR: dirRec: %s: %s\n", dirName, strerror(errno));
} else {
while((d_ent = readdir(dp)) != NULL) {
if((strcmp(d_ent->d_name, "..") != 0) && (strcmp(d_ent->d_name, ".") != 0)){
strcpy(name, dirName);
strcat(name, "/");
strcat(name, d_ent->d_name);
if(lstat(name, &s) < 0) {
printf("ERROR: dirDepth: %s: %s\n", name, strerror(errno));
} else {
if(S_ISDIR(s.st_mode)) { /* Process directories. */
printf("Directory : %s\n", name);
Enqueue(name, q);
} else { /* Process non-directories. */
printf("File : %s\n", name);
}
}
}
}
closedir(dp);
Sample Run
$ ./dir .
File : ./dir.c
File : ./dir.cpp
File : ./dir.exe
File : ./dir.exe.stackdump
File : ./dirRec.c
File : ./dirRec.exe
File : ./fatal.h
File : ./Makefile
File : ./queue.c
File : ./queue.h
File : ./stackli.c
File : ./stackli.h
Directory : ./testL1a
Directory : ./testL1b
File : ./testL1b/New Bitmap Image.bmp
ERROR: dirRec: ./testL1b/New Bitmap Image.bmp: Not a directory
We can’t see what Enqueue() does, but odds are high to you put a pointer to a string on the queue instead of a copy of the string. So yes, what you dequeue won’t be the same string again since you keep modifying name in the while loop.