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(char **entries, int count)
34 for (i = 0; i < count; i++)
40 * Our caller expects a malloc'ed array of malloc'ed string pointers.
41 * To ensure consistency when mixing this with other directory
42 * operations, we collect the entire list in one atomic operation,
43 * rather than reading the directory lazily.
47 getDirectoryContents(path)
56 /* Check for an actual directory */
57 while (stat(path, &sb) != 0) {
64 if (!S_ISDIR(sb.st_mode)) {
65 ghc_errtype = ERR_INAPPROPRIATETYPE;
66 ghc_errstr = "not a directory";
71 if ((entries = (char **) malloc(alloc * sizeof(char *))) == NULL) {
72 ghc_errtype = ERR_RESOURCEEXHAUSTED;
73 ghc_errstr = "not enough virtual memory";
77 while ((dir = opendir(path)) == NULL) {
88 errno = 0; /* unchanged by readdir on EOF */
89 while ((d = readdir(dir)) == NULL) {
91 entries[count] = NULL;
93 return (StgAddr) entries;
94 } else if (errno != EINTR) {
97 freeEntries(entries, count);
103 if ((entries[count] = malloc(strlen(d->d_name))) == NULL) {
104 ghc_errtype = ERR_RESOURCEEXHAUSTED;
105 ghc_errstr = "not enough virtual memory";
106 freeEntries(entries, count);
107 (void) closedir(dir);
110 strcpy(entries[count], d->d_name);
111 if (++count == alloc) {
113 if ((entries = (char **) realloc(entries, alloc * sizeof(char *))) == NULL) {
114 ghc_errtype = ERR_RESOURCEEXHAUSTED;
115 ghc_errstr = "not enough virtual memory";
116 freeEntries(entries, count);
117 (void) closedir(dir);