2

Ok, this question won't help me. The answers only print each file in a given directory. That's not enough. I need to actually record a list, in a struct dirent **. I have:

struct dirent **Entries;
DIR *Dir = opendir("/path/to/directory");

How would I record each entry into the Entries list, without calling realloc each iteration with a while loop. I need a faster way to record a list of items in a directory. Is there a faster way other than:

struct dirent **Entries;
DIR *Dir = opendir("/path/to/directory");
struct dirent *Entry;
unsigned int Count = 0;
while ((Entry = readdir(Dir))) {
    Count++;
}
Entries = malloc(Count*sizeof(char*));
closedir(Dir);
Dir = opendir("Some dir path"); //Also, is there a better way to reset it, other than closing it and reopening?
for (int i = 0; (Entry = readdir(Dir); i++) {
    Entries[i] = Entry;
}

Or

struct dirent **Entries;
DIR *Dir = opendir("/path/to/directory");
Dir = opendir("Some dir path");
struct dirent *Entry;
for (int i = 0; (Entry = readdir(Dir); i++) {
    Entries = realloc(Entries, i*sizeof(struct dirent*));
    Entries[i] = Entry;
}
closedir(Dir);

Like, is there a direct way to get all the contents of a directory at once, or a better way to handle a growing buffer of entries?

Help? Please?

  • 3
    Is the realloc time significant compared with the fileSystem I/O operations? – Martin James Jun 15 '20 at 22:14
  • @MartinJames I am not sure. –  Jun 15 '20 at 22:14
  • 2
    Typically you would "grow" the array when necessary by e.g., doubling its size. Also if you have some expectation about the final size, start with that capacity. This requires tracking size and capacity, but avoids a lot of extra copying when the final array is potentially large. See [this discussion](https://stackoverflow.com/questions/5232198/about-vectors-growth). If the final array will stick around for a long time, you can realloc one last time to reduce capacity to the size. – chash Jun 15 '20 at 22:27
  • 1
    Spin through the list once to count, then spin through again to read. You could also use a linked-list structure that you can chain entries on to as you discover them. You could also allocate a large buffer and if that's not enough, `realloc` again at 1.5x the size. Don't extend by 1, extend by a *factor*. – tadman Jun 15 '20 at 23:20

0 Answers0