1 /* savedir.c -- save the list of files in a directory in a string
3 Copyright 1990, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006 Free
4 Software Foundation, Inc.
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 2, or (at your option)
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, write to the Free Software Foundation,
18 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
20 /* Written by David MacKenzie <djm@gnu.ai.mit.edu>. */
28 #include <sys/types.h>
33 #ifndef _D_EXACT_NAMLEN
34 # define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
44 #ifndef NAME_SIZE_DEFAULT
45 # define NAME_SIZE_DEFAULT 512
48 /* Return a freshly allocated string containing the file names
49 in directory DIRP, separated by '\0' characters;
50 the end is marked by two '\0' characters in a row.
51 Return NULL (setting errno) if DIRP cannot be read or closed.
52 If DIRP is NULL, return NULL without affecting errno. */
55 savedirstream (DIR *dirp)
58 size_t allocated = NAME_SIZE_DEFAULT;
65 name_space = xmalloc (allocated);
69 struct dirent const *dp;
77 /* Skip "", ".", and "..". "" is returned by at least one buggy
78 implementation: Solaris 2.4 readdir on NFS file systems. */
80 if (entry[entry[0] != '.' ? 0 : entry[1] != '.' ? 1 : 2] != '\0')
82 size_t entry_size = _D_EXACT_NAMLEN (dp) + 1;
83 if (used + entry_size < used)
85 if (allocated <= used + entry_size)
89 if (2 * allocated < allocated)
93 while (allocated <= used + entry_size);
95 name_space = xrealloc (name_space, allocated);
97 memcpy (name_space + used, entry, entry_size);
101 name_space[used] = '\0';
103 if (closedir (dirp) != 0)
114 /* Return a freshly allocated string containing the file names
115 in directory DIR, separated by '\0' characters;
116 the end is marked by two '\0' characters in a row.
117 Return NULL (setting errno) if DIR cannot be opened, read, or closed. */
120 savedir (char const *dir)
122 return savedirstream (opendir (dir));
125 /* Return a freshly allocated string containing the file names
126 in directory FD, separated by '\0' characters;
127 the end is marked by two '\0' characters in a row.
128 Return NULL (setting errno) if FD cannot be read or closed. */
133 return savedirstream (fdopendir (fd));