1 /* savedir.c -- save the list of files in a directory in a string
2 Copyright 1990,97,98,99,2000, 2001 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by David MacKenzie <djm@gnu.ai.mit.edu>. */
24 #include <sys/types.h>
34 # define dirent direct
36 # include <sys/ndir.h>
47 /* Fake a return value. */
48 # define CLOSEDIR(d) (closedir (d), 0)
50 # define CLOSEDIR(d) closedir (d)
64 /* Return a freshly allocated string containing the filenames
65 in directory DIR, separated by '\0' characters;
66 the end is marked by two '\0' characters in a row.
67 Return NULL (setting errno) if DIR cannot be opened, read, or closed. */
69 #ifndef NAME_SIZE_DEFAULT
70 # define NAME_SIZE_DEFAULT 512
74 savedir (const char *dir)
79 size_t allocated = NAME_SIZE_DEFAULT;
87 name_space = xmalloc (allocated);
90 while ((dp = readdir (dirp)) != NULL)
92 /* Skip "", ".", and "..". "" is returned by at least one buggy
93 implementation: Solaris 2.4 readdir on NFS filesystems. */
94 char const *entry = dp->d_name;
95 if (entry[entry[0] != '.' ? 0 : entry[1] != '.' ? 1 : 2] != '\0')
97 size_t entry_size = strlen (entry) + 1;
98 if (used + entry_size < used)
100 if (allocated <= used + entry_size)
104 if (2 * allocated < allocated)
108 while (allocated <= used + entry_size);
110 name_space = xrealloc (name_space, allocated);
112 memcpy (name_space + used, entry, entry_size);
116 name_space[used] = '\0';
118 if (CLOSEDIR (dirp) != 0)