Debian Codegraph @

compat/opendir.c

raw
1 /*
2 * opendir.c --
3 *
4 * This file provides dirent-style directory-reading procedures for V7
5 * Unix systems that don't have such procedures. The origin of this code
6 * is unclear, but it seems to have come originally from Larry Wall.
7 */
8
9 #include "tclInt.h"
10
11 #undef DIRSIZ
12 #define DIRSIZ(dp) \
13 ((sizeof(struct dirent) - (MAXNAMLEN+1)) + (((dp)->d_namlen+1 + 3) &~ 3))
14
15 /*
16 * open a directory.
17 */
18
19 DIR *
20 opendir(
21 char *name)
22 {
23 DIR *dirp;
24 int fd;
25 const char *myname;
26
27 myname = ((*name == '\0') ? "." : name);
28 if ((fd = open(myname, 0, 0)) == -1) {
29 return NULL;
30 }
31 dirp = (DIR *) attemptckalloc(sizeof(DIR));
32 if (dirp == NULL) {
33 /* unreachable? */
34 close(fd);
35 return NULL;
36 }
37 dirp->dd_fd = fd;
38 dirp->dd_loc = 0;
39 return dirp;
40 }
41
42 /*
43 * read an old style directory entry and present it as a new one
44 */
45 #ifndef pyr
46 #define ODIRSIZ 14
47
48 struct olddirect {
49 ino_t od_ino;
50 char od_name[ODIRSIZ];
51 };
52 #else /* a Pyramid in the ATT universe */
53 #define ODIRSIZ 248
54
55 struct olddirect {
56 long od_ino;
57 short od_fill1, od_fill2;
58 char od_name[ODIRSIZ];
59 };
60 #endif
61
62 /*
63 * get next entry in a directory.
64 */
65
66 struct dirent *
67 readdir(
68 DIR *dirp)
69 {
70 struct olddirect *dp;
71 static struct dirent dir;
72
73 for (;;) {
74 if (dirp->dd_loc == 0) {
75 dirp->dd_size = read(dirp->dd_fd, dirp->dd_buf, DIRBLKSIZ);
76 if (dirp->dd_size <= 0) {
77 return NULL;
78 }
79 }
80 if (dirp->dd_loc >= dirp->dd_size) {
81 dirp->dd_loc = 0;
82 continue;
83 }
84 dp = (struct olddirect *)(dirp->dd_buf + dirp->dd_loc);
85 dirp->dd_loc += sizeof(struct olddirect);
86 if (dp->od_ino == 0) {
87 continue;
88 }
89 dir.d_ino = dp->od_ino;
90 strncpy(dir.d_name, dp->od_name, ODIRSIZ);
91 dir.d_name[ODIRSIZ] = '\0'; /* insure null termination */
92 dir.d_namlen = strlen(dir.d_name);
93 dir.d_reclen = DIRSIZ(&dir);
94 return &dir;
95 }
96 }
97
98 /*
99 * close a directory.
100 */
101
102 void
103 closedir(
104 DIR *dirp)
105 {
106 close(dirp->dd_fd);
107 dirp->dd_fd = -1;
108 dirp->dd_loc = 0;
109 ckfree((char *)dirp);
110 }