I am trying to get the contents of a directory. Ideally, I would like to store them in a string array. Is there a way to do this in c other than opening the directory, iterating through its contents, and populating an array as it goes?
I am working on a system running OS X 10.9
You can obtain an allocated directory listing with the POSIX scandir function, which takes a path and optional filtering and sorting callbacks, and returns an array of dirent
structures. OS X also provides an equivalent function which takes blocks rather than callbacks for sorting and filtering.
int scandir(const char *dirname, struct dirent ***namelist,
int (*select)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
Just retrieving an unsorted list of entries is very straightforward:
int num_entries;
struct dirent **entries = NULL;
num_entries = scandir("/", &entries, NULL, NULL);
for(int i = 0; i < num_entries; i++)
puts(entries[i]->d_name);
//entries is ours to free
for(int i = 0; i < num_entries; i++)
free(entries[i]);
free(entries);
POSIX also provides a pre-made sorting function to use with scandir for alphabetical ordering. To use it, just pass alphasort
as the last argument.
Be careful of scandir returning an error (-1). The above code is structured in such a way that an explicit check isn't necessary, but that may not be possible in more elaborate uses.