I want a function that returns the content of a given directory. For this, I am using scandir from dirent.h. The code below compiles successfully (gcc -Wall test.c), but the last printf leads to a segmentation fault. It means that the “eps” structure (a pointer to an array of pointers to dirent structures) is still empty after the function: how can I fix this?
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
static int myselector(const struct dirent * dir_entry)
{
char * pch = strstr(dir_entry->d_name, ".");
return pch == NULL ? 1 : 0;
}
int list_dir(char * dirname, struct dirent ** eps)
{
int nbfiles = scandir(dirname, &eps, myselector, alphasort);
if(nbfiles > 0)
{
printf("inside function: %s\n", eps[0]->d_name);
return 1;
}
else
return 0;
}
int main(int argc, char *argv[])
{
int status = 0;
struct dirent ** eps = NULL;
status = list_dir("/home", eps);
if (status)
{
puts("ok");
printf("outside function: %s\n", eps[0]->d_name);
}
return EXIT_SUCCESS;
}
Because your pointer has changed, and you’re looking at the wrong thing in
main()🙂You’re passing a pointer to a pointer to a pointer to
scandir(). it’s changing what the pointer to a pointer is pointing at (I know, that hurts to read … ).Because you’re calling
scandir()with&epsin your function, you lose that change outside of the function. The value ofepshas changed inside your function.To better understand this, in your current function wrap the
scandir()call withprintf()statements showing you what the value contained inepsis:To fix this change your function to:
And call it as …
in
main(). It will then work perfectly: