Reputation: 365
I thought this would be pretty academic but its not. I'm trying to traverse a directory try (recursively). However, I keep getting the following message when calling readdir():
./xsed.bin
make: *** [run] Segmentation fault
GDB has the following output when tracing though the program:
Breakpoint 1, recurseDir (path=0x401090 ".") at xsed.c:216
216 DIR *currD = opendir(path);
(gdb) n
217 if( currD = NULL)
(gdb) n
226 entry = readdir(currD);
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7afef86 in __readdir (dirp=0x0) at ../sysdeps/unix/readdir.c:45
45 ../sysdeps/unix/readdir.c: No such file or directory.
in ../sysdeps/unix/readdir.c
I've read several places never to call readdir() twice on the same Dir* object. I'm getting a segfault when calling it once. I've checked the path string to ensure its correct (e.g. using "." or "./" etc)-- no luck.
Here's the code below: Called like: recurseDir(getcwd(currD,256)) or recurseDir(".");
void recurseDir(char *path)
{
DIR *currD = opendir(path);
if( currD = NULL)
{
fprintf(stderr,"Could not open directory: %s\n",path);
return;
}
else
{
struct dirent *entry;
char *dName;
entry = readdir(currD); <--- segfault
if( entry == NULL)
{
fprintf(stderr,"Error reading directory.\n");
return;
}
dName = entry->d_name;
printf("Current dir:%s\n",dName);
}
}
I have no idea how the argument (dirp) is getting to be NULL inside the call to readdir(). NOTE: This is happening during the first call to recurseDir(), no recursion happens at all. I'm I off or is this a compiler/machine thing?
Please help!!!!
Upvotes: 0
Views: 3200
Reputation: 4713
For one thing, you have if( currD = NULL)
. You probably meant ==
rather than =
. Yep, that would definitely explain why your currD
is NULL. :-)
By the way, some people prefer to write NULL == currD
to guard against this. Or you could just say !currD
.
Upvotes: 2