C - OpenDir() Number of Entries -


after getting dir * using opendir(), need use readdir() read , store struct dirent array.

in order figure out size of array, loop through , count entries. then, allocate array , loop through again read , store struct dirent.

however, i'm wondering whether there better way number of dir entries?

the realloc way best way go. here's example (small allocation size chosen demo purposes.) no error checking performed. @ end of loop, direntarray has goods, , count tells how many there are.

#define num_to_alloc 10  int main(int argc, const char * argv[]) {      struct dirent *direntarray = null;      dir *mydir = opendir("/tmp");     int count = 0;     int max = 0;     struct dirent *myent;      while ((myent = readdir(mydir))){         if ( count == max ){             max += num_to_alloc;             direntarray = realloc(direntarray, max * sizeof(struct dirent));         }         memcpy(&direntarray[count], myent, sizeof(struct dirent));         count++;     }     return 0;  } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -