9 int scandir(const char *path
, struct dirent
***res
,
10 int (*sel
)(const struct dirent
*),
11 int (*cmp
)(const struct dirent
**, const struct dirent
**))
13 DIR *d
= opendir(path
);
14 struct dirent
*de
, **names
=0, **tmp
;
16 int old_errno
= errno
;
20 while ((errno
=0), (de
= readdir(d
))) {
21 if (sel
&& !sel(de
)) continue;
24 if (len
> SIZE_MAX
/sizeof *names
) break;
25 tmp
= realloc(names
, len
* sizeof *names
);
29 names
[cnt
] = malloc(de
->d_reclen
);
30 if (!names
[cnt
]) break;
31 memcpy(names
[cnt
++], de
, de
->d_reclen
);
37 if (names
) while (cnt
-->0) free(names
[cnt
]);
43 if (cmp
) qsort(names
, cnt
, sizeof *names
, (int (*)(const void *, const void *))cmp
);