1 /* Copyright (C) 1992, 1995, 1996 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Ian Lance Taylor (ian@airs.com).
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with the GNU C Library; see the file COPYING.LIB. If
17 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
18 Cambridge, MA 02139, USA. */
26 #include <sys/types.h>
32 #define PATH_MAX 1024 /* XXX */
36 /* Traverse one level of a directory tree. */
39 DEFUN (ftw_dir, (dirs, level, descriptors, dir, len, func),
40 DIR **dirs AND int level AND int descriptors AND
41 char *dir AND size_t len AND
42 int EXFUN((*func), (CONST char *file, struct stat *status,
52 while ((entry = readdir (dirs[level])) != NULL)
55 int flag, retval, newlev;
60 if (entry->d_name[0] == '.'
61 && (entry->d_name[1] == '\0' ||
62 (entry->d_name[1] == '.' && entry->d_name[2] == '\0')))
68 namlen = _D_EXACT_NAMLEN (entry);
70 if (namlen + len + 1 > PATH_MAX)
81 memcpy ((PTR) (dir + len + 1), (PTR) entry->d_name,
84 if (stat (dir, &s) < 0)
86 if (errno != EACCES && errno != ENOENT)
90 else if (S_ISDIR (s.st_mode))
92 newlev = (level + 1) % descriptors;
94 if (dirs[newlev] != NULL)
95 closedir (dirs[newlev]);
97 dirs[newlev] = opendir (dir);
98 if (dirs[newlev] != NULL)
110 retval = (*func) (dir, &s, flag);
115 retval = ftw_dir (dirs, newlev, descriptors, dir,
116 namlen + len + 1, func);
117 if (dirs[newlev] != NULL)
122 closedir (dirs[newlev]);
131 if (dirs[level] == NULL)
136 dirs[level] = opendir (dir);
137 if (dirs[level] == NULL)
143 if (readdir (dirs[level]) == NULL)
144 return errno == 0 ? 0 : -1;
151 return errno == 0 ? 0 : -1;
154 /* Call a function on every element in a directory tree. */
157 DEFUN(ftw, (dir, func, descriptors),
159 int EXFUN((*func), (CONST char *file, struct stat *status,
165 char buf[PATH_MAX + 1];
170 if (descriptors <= 0)
173 dirs = (DIR **) __alloca (descriptors * sizeof (DIR *));
178 if (stat (dir, &s) < 0)
180 if (errno != EACCES && errno != ENOENT)
184 else if (S_ISDIR (s.st_mode))
186 dirs[0] = opendir (dir);
200 memcpy ((PTR) buf, (PTR) dir, len + 1);
202 retval = (*func) (buf, &s, flag);
207 retval = ftw_dir (dirs, 0, descriptors, buf, len, func);