1 /* savedir.c -- save the list of files in a directory in a string
2 Copyright (C) 1990, 1997, 1998 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>
32 # define NAMLEN(dirent) strlen((dirent)->d_name)
34 # define dirent direct
35 # define NAMLEN(dirent) (dirent)->d_namlen
37 # include <sys/ndir.h>
48 /* Fake a return value. */
49 # define CLOSEDIR(d) (closedir (d), 0)
51 # define CLOSEDIR(d) closedir (d)
71 /* Return a freshly allocated string containing the filenames
72 in directory DIR, separated by '\0' characters;
73 the end is marked by two '\0' characters in a row.
74 NAME_SIZE is the number of bytes to initially allocate
75 for the string; it will be enlarged as needed.
76 Return NULL if DIR cannot be opened or if out of memory. */
79 savedir (const char *dir
, unsigned int name_size
)
90 name_space
= (char *) malloc (name_size
);
91 if (name_space
== NULL
)
98 while ((dp
= readdir (dirp
)) != NULL
)
100 /* Skip "." and ".." (some NFS filesystems' directories lack them). */
101 if (dp
->d_name
[0] != '.'
102 || (dp
->d_name
[1] != '\0'
103 && (dp
->d_name
[1] != '.' || dp
->d_name
[2] != '\0')))
105 unsigned size_needed
= (namep
- name_space
) + NAMLEN (dp
) + 2;
107 if (size_needed
> name_size
)
109 char *new_name_space
;
111 while (size_needed
> name_size
)
114 new_name_space
= realloc (name_space
, name_size
);
115 if (new_name_space
== NULL
)
120 namep
+= new_name_space
- name_space
;
121 name_space
= new_name_space
;
123 namep
= stpcpy (namep
, dp
->d_name
) + 1;