I'm writing a c program to read the files and directories from a directory and then point the number of elements found in a data of a struct and point the name of the elements in a dynamic array in a data of the same struct. I did it and its output is right. The problem is that when I run the program a "Segmentation fault (core dumped)" shows up.
The code:
#include <stdio.h>
#include <dirent.h>
#define EXIT_FAILURE 1
typedef struct FileDir
{
int *n_files;
char *file_name[];
} FileDir;
int get_files_within_dir(struct FileDir *fd)
{
DIR *dir;
int n_files;
int index;
n_files = 0;
if ((dir = opendir ("/tmp")) != NULL) {
/* counts all the files and directories within directory */
while (readdir (dir) != NULL) {
n_files++;
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
char *file_name[n_files];
struct dirent *ent;
if ((dir = opendir ("/tmp")) != NULL) {
/* gets all the files and directories within directory */
index = 0;
while ((ent = readdir (dir)) != NULL) {
file_name[index++] = ent->d_name;
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
fd->n_files = n_files;
fd->file_name[0] = file_name[0];
fd->file_name[1] = file_name[1];
fd->file_name[2] = file_name[2];
fd->file_name[3] = file_name[3];
return 0;
}
int main()
{
struct FileDir fd;
get_files_within_dir(&fd);
printf("%d\n", fd.n_files);
printf("%s\n", fd.file_name[1]);
printf("%s\n", fd.file_name[2]);
printf("%s\n", fd.file_name[3]);
return 0;
}
The output:
[freitas@localhost src]$ ./file_dir
21
..
geany_socket.fcda02b3
tmpiSdUX3
Segmentation fault (core dumped)
The interesting thing is that if I just point less than or equal to 2 values to the dynamic array of the data of the struct the error message does not show up. Do you have any idea ?
Thank you!