dynamic array ?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • David d'Angers

    #1

    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

  • Mark Bluemel

    #2
    Re: dynamic array ?

    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.

    Comment

    • David d'Angers

      #3
      Re: dynamic array ?

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

      Comment

      • santosh

        #4
        Re: dynamic array ?

        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_INITIA L_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_INITIA L_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 */

        Comment

        • David d'Angers

          #5
          Re: dynamic array ?

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

          Comment

          Working...