Hi.
I`m struggling with the following function for almost 2 hours now and I can`t figure out what is the problem with it, maybe you can help me.
The function lists the files and folders in a specified folder, and loads the result into a FileData array.
Code:
typedef struct
{
char *fileName;
int isFile;
} FileData;
FileData **fs_listFiles(const char *path)
{
DIR *dir;
struct dirent *ent;
FileData **fd;
int i;
dir = opendir (path);
if (dir != NULL)
{
while ((ent = readdir (dir)) != NULL)
{
fd[i] = (FileData **)malloc(sizeof(FileData*));
fd[i]->fileName = ent->d_name;
printf("%s\n",fd[i]->fileName);
i++;
}
closedir (dir);
return fd;
}
return NULL;
}
When I run this piece of code, it breaks with segmentation faul at the fd[i]->fileName = ent->d_name; part. I also tried to use realloc like this: fd = (FileData **)realloc((void *)fd, sizeof(FileData*)*(i+1)); but still no luck.
If i print the size of the allocated memory for the fd variable it doesnt break, and the size itself seems to be ok.
Can anybody help me?
Thank you.