2 % (c) The GRASP/AQUA Project, Glasgow University, 1995
4 \subsection[getDirectoryContents.lc]{getDirectoryContents Runtime Support}
11 #ifdef HAVE_SYS_TYPES_H
12 #include <sys/types.h>
15 #ifdef HAVE_SYS_STAT_H
27 /* For cleanup of partial answer on error */
30 freeEntries(entries, count)
36 for (i = 0; i < count; i++)
42 * Our caller expects a malloc'ed array of malloc'ed string pointers.
43 * To ensure consistency when mixing this with other directory
44 * operations, we collect the entire list in one atomic operation,
45 * rather than reading the directory lazily.
49 getDirectoryContents(path)
58 /* Check for an actual directory */
59 while (stat(path, &sb) != 0) {
66 if (!S_ISDIR(sb.st_mode)) {
67 ghc_errtype = ERR_INAPPROPRIATETYPE;
68 ghc_errstr = "not a directory";
73 if ((entries = (char **) malloc(alloc * sizeof(char *))) == NULL) {
74 ghc_errtype = ERR_RESOURCEEXHAUSTED;
75 ghc_errstr = "not enough virtual memory";
79 while ((dir = opendir(path)) == NULL) {
90 errno = 0; /* unchanged by readdir on EOF */
91 while ((d = readdir(dir)) == NULL) {
93 entries[count] = NULL;
95 return (StgAddr) entries;
96 } else if (errno != EINTR) {
99 freeEntries(entries, count);
100 (void) closedir(dir);
105 if ((entries[count] = malloc(strlen(d->d_name))) == NULL) {
106 ghc_errtype = ERR_RESOURCEEXHAUSTED;
107 ghc_errstr = "not enough virtual memory";
108 freeEntries(entries, count);
109 (void) closedir(dir);
112 strcpy(entries[count], d->d_name);
113 if (++count == alloc) {
115 if ((entries = (char **) realloc(entries, alloc * sizeof(char *))) == NULL) {
116 ghc_errtype = ERR_RESOURCEEXHAUSTED;
117 ghc_errstr = "not enough virtual memory";
118 freeEntries(entries, count);
119 (void) closedir(dir);