[project @ 2003-02-04 11:55:54 by simonmar]
[haskell-directory.git] / cbits / dirUtils.c
1 /* 
2  * (c) The University of Glasgow 2002
3  *
4  * Directory Runtime Support
5  */
6
7 #include "config.h"
8
9 // The following is required on Solaris to force the POSIX versions of
10 // the various _r functions instead of the Solaris versions.
11 #ifdef solaris2_TARGET_OS
12 #define _POSIX_PTHREAD_SEMANTICS
13 #endif
14
15 #include "HsBase.h"
16
17 #if defined(mingw32_TARGET_OS)
18 #include <windows.h>
19 #endif
20
21 /*
22  * read an entry from the directory stream; opt for the
23  * re-entrant friendly way of doing this, if available.
24  */
25 HsInt
26 __hscore_readdir( HsAddr dirPtr, HsAddr pDirEnt )
27 {
28   struct dirent **pDirE = (struct dirent**)pDirEnt;
29 #if HAVE_READDIR_R
30   struct dirent* p;
31   int res;
32   static unsigned int nm_max = -1;
33   
34   if (pDirE == NULL) {
35     return -1;
36   }
37   if (nm_max == -1) {
38 #ifdef NAME_MAX
39     nm_max = NAME_MAX + 1;
40 #else
41     nm_max = pathconf(".", _PC_NAME_MAX);
42     if (nm_max == -1) { nm_max = 255; }
43     nm_max++;
44 #endif
45   }
46   p = (struct dirent*)malloc(sizeof(struct dirent) + nm_max);
47   if (p == NULL) return -1;
48   res = readdir_r((DIR*)dirPtr, p, pDirE);
49   if (res != 0) {
50     *pDirE = NULL;
51     free(p);
52   }
53   return res;
54 #else
55
56   if (pDirE == NULL) {
57     return -1;
58   }
59
60   *pDirE = readdir((DIR*)dirPtr);
61   if (*pDirE == NULL) {
62     return -1;
63   } else {
64     return 0;
65   }  
66 #endif
67 }