469,578 Members | 1,421 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,578 developers. It's quick & easy.

dynamic array ?

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

Oct 22 '07 #1
4 1388
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 ?
Look at the manual page for realloc...
can anyone post some code snippets please?
Someone might, but I'm afraid it won't be me.
Oct 22 '07 #2
thanks
you've helped already
i should be looking at dynamic memory allocation

Oct 22 '07 #3
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 */

Oct 22 '07 #4
thanks goto santosh with all my heart
i was just feeling confused about the fact that each element in the
array is itself unknown

Oct 22 '07 #5

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by Vasileios Zografos | last post: by
4 posts views Thread by Scott Lyons | last post: by
5 posts views Thread by meyousikmann | last post: by
8 posts views Thread by Peter B. Steiger | last post: by
6 posts views Thread by Materialised | last post: by
reply views Thread by pjr | last post: by
13 posts views Thread by kwikius | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.