1 /* $XConsortium: savedir.c,v 1.1 94/04/13 18:26:54 rws Exp $ */
2 /* savedir.c -- save the list of files in a directory in a string
3 Copyright 1990, 1993 Free Software Foundation, Inc.
5 Permission to use, copy, modify, and distribute this program for
6 any purpose and without fee is hereby granted, provided that this
7 copyright and permission notice appear on all copies, and that
8 notice be given that copying and distribution is by permission of
9 the Free Software Foundation. The Free Software Foundation makes
10 no representations about the suitability of this software for any
11 purpose. It is provided "as is" without expressed or implied
14 (The FSF has modified its usual distribution terms, for this file,
15 as a courtesy to the X project.) */
17 /* Written by David MacKenzie <djm@ai.mit.edu>.
18 Modified to use <dirent.h> by default. Per Bothner <bothner@cygnus.com>. */
20 #include <sys/types.h>
21 #if !defined(DIRECT) && !defined(BSD)
23 #define NLENGTH(direct) (strlen((direct)->d_name))
27 #define NLENGTH(direct) ((direct)->d_namlen)
39 #if defined(VOID_CLOSEDIR) || defined(BSD)
40 /* Fake a return value. */
41 #define CLOSEDIR(d) (closedir (d), 0)
43 #define CLOSEDIR(d) closedir (d)
60 /* Return a freshly allocated string containing the filenames
61 in directory DIR, separated by '\0' characters;
62 the end is marked by two '\0' characters in a row.
63 NAME_SIZE is the number of bytes to initially allocate
64 for the string; it will be enlarged as needed.
65 Return NULL if DIR cannot be opened or if out of memory. */
68 savedir (dir, name_size)
81 name_space = (char *) malloc (name_size);
82 if (name_space == NULL)
89 while ((dp = readdir (dirp)) != NULL)
91 /* Skip "." and ".." (some NFS filesystems' directories lack them). */
92 if (dp->d_name[0] != '.'
93 || (dp->d_name[1] != '\0'
94 && (dp->d_name[1] != '.' || dp->d_name[2] != '\0')))
96 unsigned size_needed = (namep - name_space) + NLENGTH (dp) + 2;
98 if (size_needed > name_size)
100 char *new_name_space;
102 while (size_needed > name_size)
105 new_name_space = realloc (name_space, name_size);
106 if (new_name_space == NULL)
111 namep += new_name_space - name_space;
112 name_space = new_name_space;
114 strcpy (namep, dp->d_name);
115 namep += strlen (namep) + 1;