1 /* savedir.c -- save the list of files in a directory in a string
2 Copyright (C) 1990 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
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
18 /* Written by David MacKenzie <djm@ai.mit.edu>. */
20 #include <sys/types.h>
27 #define NLENGTH(direct) (strlen((direct)->d_name))
29 #define NLENGTH(direct) ((direct)->d_namlen)
42 /* Fake a return value. */
43 #define CLOSEDIR(d) (closedir (d), 0)
45 #define CLOSEDIR(d) closedir (d)
61 /* Return a freshly allocated string containing the filenames
62 in directory DIR, separated by '\0' characters;
63 the end is marked by two '\0' characters in a row.
64 NAME_SIZE is the number of bytes to initially allocate
65 for the string; it will be enlarged as needed.
66 Return NULL if DIR cannot be opened or if out of memory. */
69 savedir (dir
, name_size
)
82 name_space
= (char *) malloc (name_size
);
83 if (name_space
== NULL
)
90 while ((dp
= readdir (dirp
)) != NULL
)
92 /* Skip "." and ".." (some NFS filesystems' directories lack them). */
93 if (dp
->d_name
[0] != '.'
94 || (dp
->d_name
[1] != '\0'
95 && (dp
->d_name
[1] != '.' || dp
->d_name
[2] != '\0')))
97 unsigned size_needed
= (namep
- name_space
) + NLENGTH (dp
) + 2;
99 if (size_needed
> name_size
)
101 char *new_name_space
;
103 while (size_needed
> name_size
)
106 new_name_space
= realloc (name_space
, name_size
);
107 if (new_name_space
== NULL
)
112 namep
+= new_name_space
- name_space
;
113 name_space
= new_name_space
;
115 namep
= stpcpy (namep
, dp
->d_name
) + 1;