What is the fastest way to record the listed files in a directory in C? I want to fill an array of dirent pointers with each entry of a specified directory. I either need to count the items before, allocate memory, then go over them again, or I will have to reallocate each iteration of the while loop. Both of these options seem slow. Surely there's a better way.
Are these my only option:
struct dirent **Entries;
DIR *Dir = opendir(&quot;Some dir path&quot;);
struct dirent *Entry;
unsigned int Count = 0;
while ((Entry = readdir(Dir))) {
    Count++;
}
Entries = malloc(Count*sizeof(struct dirent*));
rewinddir(Dir);
for (int i = 0; (Entry = readdir(Dir); i++) {
    Entries[i] = Entry;
}

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

Or is there some faster way?
OP poses 2 approaches

Iterate twice through opendir(), readdir(), closedir() with one malloc().

Iterate one through opendir(), readdir(), closedir() with multiple realloc().


For performance, I would use a 3rd option: linked list instead of using an array of struct dirent

Iterate once through opendir(), readdir(), closedir() with one malloc() per entry.


As with such performance issue: strive for reduced big O, not linear ones.