Hello,

I am trying to read through a UNIX directory in C and write all the filenames to an array. However, the array is not being populated with any value. Here is a snippet of relevant code:

char **files = {NULL};
struct stat fileinfo;
int count = 0;
int status = 0;
struct dirent *entry;
dir *dir_ptr = opendir(".");

/*First count number of files, exclude directories */
                while ((entry = readdir (dir_ptr)) != NULL) {
                        status = stat (entry->d_name, &fileinfo);
                        if (status != 0) {
                                fprintf (stderr, "STAT Failed!!!\n");
                                exit (0);
                        }
                        if (strcmp (entry->d_name, ".") == 0 || strcmp (entry->d_name, "..") == 0) {
                                continue;
                        }
                        if (!S_ISDIR(fileinfo.st_mode)) {
                                count++;
                        }
                        else {
                                continue;
                        }
                }
                /* malloc the data */
                files = (char **)malloc(count*sizeof(char*));
                count = 0;
                closedir (dir_ptr);
                /* read through directory again and write files to array */
                dir_ptr = opendir (".");
                while ((entry = readdir (dir_ptr)) != NULL) {
                        status = stat (entry->d_name, &fileinfo);
                        if (status != 0) {
                                fprintf (stderr, "STAT Failed!!!\n");
                                exit (0);
                        }
                        if (strcmp (entry->d_name, ".") == 0 || strcmp (entry->d_name, "..") == 0) {
                                continue;
                        }
                        if (!S_ISDIR(fileinfo.st_mode)) {
                                files[count] = entry->d_name;
                                count++;
                        }
                        else {
                                continue;
                        }
                }

Edited 6 Years Ago by ItecKid: n/a

The entry returned by readdir is statically allocated. That is, you end up with only one instance of it, and all the pointers in the files array will have the same value.
You need to hold each d_name individually: replace line 41 with

files[count] = strdup(entry->d_name);
This question has already been answered. Start a new discussion instead.