recurse_dir.c (1003B)
1 /* see LICENSE file for copyright and license details */ 2 #include <dirent.h> 3 #include <limits.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 #include <sys/stat.h> 8 #include <sys/types.h> 9 #include <unistd.h> 10 11 #include "../util.h" 12 13 void 14 recurse_dir(const char *path, void (*fn)(const char *)) 15 { 16 char buf[PATH_MAX]; 17 struct dirent *d; 18 struct stat st; 19 DIR *dp; 20 21 if (lstat(path, &st) == -1 || S_ISDIR(st.st_mode) == 0) 22 return; 23 24 if (!(dp = opendir(path))) 25 eprintf("opendir %s:", path); 26 27 while ((d = readdir(dp))) { 28 if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) 29 continue; 30 if (strlcpy(buf, path, sizeof(buf)) >= sizeof(buf)) 31 eprintf("path too long\n"); 32 if (buf[strlen(buf) - 1] != '/') 33 if (strlcat(buf, "/", sizeof(buf)) >= sizeof(buf)) 34 eprintf("path too long\n"); 35 if (strlcat(buf, d->d_name, sizeof(buf)) >= sizeof(buf)) 36 eprintf("path too long\n"); 37 fn(buf); 38 } 39 40 closedir(dp); 41 }