Fix three PyChecker-detected gotchas.
[python/dscho.git] / Mac / Compat / opendir.c
bloba015609a186df5bfa446f1aab1becd9e8346fa94
1 /*
2 * Macintosh version of UNIX directory access package
3 * (opendir, readdir, closedir).
4 * Public domain by Guido van Rossum, CWI, Amsterdam (July 1987).
5 */
7 #include "dirent.h"
8 #include "macdefs.h"
10 static DIR opened;
13 * Open a directory. This means calling PBOpenWD.
14 * The value returned is always the address of opened, or NULL.
15 * (I have as yet no use for multiple open directories; this could
16 * be implemented by allocating memory dynamically.)
19 DIR *
20 opendir(path)
21 char *path;
23 #if TARGET_API_MAC_CARBON
24 Str255 ppath;
25 FSSpec fss;
26 int plen;
27 OSErr err;
29 if (opened.nextfile != 0) {
30 errno = EBUSY;
31 return NULL; /* A directory is already open. */
33 plen = strlen(path);
34 c2pstrcpy(ppath, path);
35 if ( ppath[plen] != ':' )
36 ppath[++plen] = ':';
37 ppath[++plen] = 'x';
38 ppath[0] = plen;
39 if( (err = FSMakeFSSpec(0, 0, ppath, &fss)) < 0 && err != fnfErr ) {
40 errno = EIO;
41 return NULL;
43 opened.dirid = fss.parID;
44 opened.vrefnum = fss.vRefNum;
45 opened.nextfile = 1;
46 return &opened;
47 #else
48 union {
49 WDPBRec d;
50 VolumeParam v;
51 } pb;
52 char ppath[MAXPATH];
53 short err;
55 if (opened.nextfile != 0) {
56 errno = EBUSY;
57 return NULL; /* A directory is already open. */
59 strncpy(ppath+1, path, ppath[0]= strlen(path));
60 pb.d.ioNamePtr= (unsigned char *)ppath;
61 pb.d.ioVRefNum= 0;
62 pb.d.ioWDProcID= 0;
63 pb.d.ioWDDirID= 0;
64 err= PBOpenWD((WDPBPtr)&pb, 0);
65 if (err != noErr) {
66 errno = ENOENT;
67 return NULL;
69 opened.dirid= pb.d.ioVRefNum;
70 opened.nextfile= 1;
71 return &opened;
72 #endif
76 * Close a directory.
79 void
80 closedir(dirp)
81 DIR *dirp;
83 #if TARGET_API_MAC_CARBON
84 dirp->nextfile = 0;
85 #else
86 WDPBRec pb;
88 pb.ioVRefNum= dirp->dirid;
89 (void) PBCloseWD(&pb, 0);
90 dirp->dirid= 0;
91 dirp->nextfile= 0;
92 #endif
96 * Read the next directory entry.
99 struct dirent *
100 readdir(dp)
101 DIR *dp;
103 union {
104 DirInfo d;
105 FileParam f;
106 HFileInfo hf;
107 } pb;
108 short err;
109 static struct dirent dir;
111 dir.d_name[0]= 0;
112 pb.d.ioNamePtr= (unsigned char *)dir.d_name;
113 #if TARGET_API_MAC_CARBON
114 pb.d.ioVRefNum= dp->vrefnum;
115 pb.d.ioDrDirID= dp->dirid;
116 #else
117 pb.d.ioVRefNum= dp->dirid;
118 pb.d.ioDrDirID= 0;
119 #endif
120 pb.d.ioFDirIndex= dp->nextfile++;
121 err= PBGetCatInfo((CInfoPBPtr)&pb, 0);
122 if (err != noErr) {
123 errno = EIO;
124 return NULL;
126 #if TARGET_API_MAC_CARBON
127 p2cstrcpy(dir.d_name, (StringPtr)dir.d_name);
128 #else
129 (void) p2cstr((unsigned char *)dir.d_name);
130 #endif
131 return &dir;