David d'Angers wrote:
hi all
i need a function that returns all the file names contained in a
directory
since the number of files is not known in advance
how should i go about to use "dynamic array" to hold the file names ?
can anyone post some code snippets please?
thanks
One strategy might be to use an array of char *.
char **files = malloc(WHATEVER_INITIAL_SIZE * sizeof *files);
This sets up `files` to point to an array of char * of
WHATEVER_INITIAL_SIZE elements.
Now you can initialise each element in the array to point a block of
char objects to hold each directory entry like this:
files[ctr] = malloc(FILENAME_LENGTH * sizeof **files);
If the number of directory entires is more than WHATEVER_INITIAL_SIZE,
then you can use realloc to expand the array. Be sure to preserve your
old value for files before calling realloc, since it'll return NULL on
failure but will still leave the old block untouched.
char **tmp = realloc(files, NEW_SIZE);
if (tmp != NULL) files = tmp;
/* proceed */