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;
}
}