dynamic array ?

D

David d'Angers

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
 
M

Mark Bluemel

David said:
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.
 
D

David d'Angers

thanks
you've helped already
i should be looking at dynamic memory allocation
 
S

santosh

David said:
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 */
 
D

David d'Angers

thanks goto santosh with all my heart
i was just feeling confused about the fact that each element in the
array is itself unknown
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top