Note that you'll need to pass a directory name to opendir()
.
This is simple example of how to read and save them into a buffer. It doubles the pointers every time it hits the limit. Modern operating systems will clean up the memory allocated once process dies. Ideally, you should also call free()
in case of failures.
#include<stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include<string.h>
#include<stdlib.h>
int main(void)
{
size_t i = 0, j;
size_t size = 1;
char **names , **tmp;
DIR *directory;
struct dirent *dir;
names = malloc(size * sizeof *names); //Start with 1
directory = opendir(".");
if (!directory) { puts("opendir failed"); exit(1); }
while ((dir = readdir(directory)) != NULL) {
names[i]=strdup(dir->d_name);
if(!names[i]) { puts("strdup failed."); exit(1); }
i++;
if (i>=size) { // Double the number of pointers
tmp = realloc(names, size*2*sizeof *names );
if(!tmp) { puts("realloc failed."); exit(1); }
else { names = tmp; size*=2; }
}
}
for ( j=0 ; j<i; j++)
printf("Entry %zu: %s\n", j+1, names[j]);
closedir(directory);
}