Refactor recurse()

Instead of allocating a buffer on each run, build a buf on the stack.
This commit is contained in:
FRIGN 2015-03-12 13:22:37 +01:00
parent c4e0080bbf
commit af61ba738c
1 changed files with 10 additions and 9 deletions

View File

@ -20,8 +20,7 @@ recurse(const char *path, void (*fn)(const char *, int, void *), int depth, void
struct dirent *d; struct dirent *d;
struct stat lst, st, dst; struct stat lst, st, dst;
DIR *dp; DIR *dp;
size_t len; char subpath[PATH_MAX];
char *buf;
if (lstat(path, &lst) < 0) { if (lstat(path, &lst) < 0) {
if (errno != ENOENT) if (errno != ENOENT)
@ -40,18 +39,20 @@ recurse(const char *path, void (*fn)(const char *, int, void *), int depth, void
if (!(dp = opendir(path))) if (!(dp = opendir(path)))
eprintf("opendir %s:", path); eprintf("opendir %s:", path);
len = strlen(path);
while ((d = readdir(dp))) { while ((d = readdir(dp))) {
if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, "..")) if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
continue; continue;
buf = emalloc(len + (path[len - 1] != '/') + strlen(d->d_name) + 1); if (strlcpy(subpath, path, PATH_MAX) >= PATH_MAX)
sprintf(buf, "%s%s%s", path, (path[len - 1] == '/') ? "" : "/", d->d_name); eprintf("strlcpy: path too long\n");
if (recurse_samedev && lstat(buf, &dst) < 0) { if (path[strlen(path) - 1] != '/' && strlcat(subpath, "/", PATH_MAX) >= PATH_MAX)
eprintf("strlcat: path too long\n");
if (strlcat(subpath, d->d_name, PATH_MAX) >= PATH_MAX)
eprintf("strlcat: path too long\n");
if (recurse_samedev && lstat(subpath, &dst) < 0) {
if (errno != ENOENT) if (errno != ENOENT)
weprintf("stat %s:", buf); weprintf("stat %s:", subpath);
} else if (!(recurse_samedev && dst.st_dev != lst.st_dev)) } else if (!(recurse_samedev && dst.st_dev != lst.st_dev))
fn(buf, depth + 1, data); fn(subpath, depth + 1, data);
free(buf);
} }
closedir(dp); closedir(dp);