1 /* savedir.c -- save the list of files in a directory in a string
3 Copyright (C) 1990, 1997-2001, 2003-2006, 2009-2011 Free Software
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19 /* Written by David MacKenzie <djm@gnu.ai.mit.edu>. */
25 #include <sys/types.h>
30 #ifndef _D_EXACT_NAMLEN
31 # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
40 #ifndef NAME_SIZE_DEFAULT
41 # define NAME_SIZE_DEFAULT 512
44 /* Return a freshly allocated string containing the file names
45 in directory DIRP, separated by '\0' characters;
46 the end is marked by two '\0' characters in a row.
47 Return NULL (setting errno) if DIRP cannot be read.
48 If DIRP is NULL, return NULL without affecting errno. */
51 streamsavedir (DIR *dirp)
54 size_t allocated = NAME_SIZE_DEFAULT;
61 name_space = xmalloc (allocated);
65 struct dirent const *dp;
73 /* Skip "", ".", and "..". "" is returned by at least one buggy
74 implementation: Solaris 2.4 readdir on NFS file systems. */
76 if (entry[entry[0] != '.' ? 0 : entry[1] != '.' ? 1 : 2] != '\0')
78 size_t entry_size = _D_EXACT_NAMLEN (dp) + 1;
79 if (used + entry_size < used)
81 if (allocated <= used + entry_size)
85 if (2 * allocated < allocated)
89 while (allocated <= used + entry_size);
91 name_space = xrealloc (name_space, allocated);
93 memcpy (name_space + used, entry, entry_size);
97 name_space[used] = '\0';
108 /* Like savedirstreamp (DIRP), except also close DIRP. */
111 savedirstream (DIR *dirp)
113 char *name_space = streamsavedir (dirp);
114 if (dirp && closedir (dirp) != 0)
116 int save_errno = errno;
124 /* Return a freshly allocated string containing the file names
125 in directory DIR, separated by '\0' characters;
126 the end is marked by two '\0' characters in a row.
127 Return NULL (setting errno) if DIR cannot be opened, read, or closed. */
130 savedir (char const *dir)
132 return savedirstream (opendir (dir));
135 /* Return a freshly allocated string containing the file names
136 in directory FD, separated by '\0' characters;
137 the end is marked by two '\0' characters in a row.
138 Return NULL (setting errno) if FD cannot be read or closed. */
144 return savedirstream (fdopendir (fd));