00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050 #include <stdlib.h>
00051 #include <sys/stat.h>
00052 #include <unistd.h>
00053 #include <sys/types.h>
00054 #include <errno.h>
00055 #include <fcntl.h>
00056 #include <dirent.h>
00057
00058 #define DIR_BUF_BITS 9
00059 #define DIR_BUF_SIZE (1<<DIR_BUF_BITS)
00060
00061 struct dir_buf {
00062 int fd;
00063 int nbytes, ofs;
00064 off_t seekpos;
00065 char buf[DIR_BUF_SIZE];
00066 };
00067
00068 DIR *opendir(const char *dname)
00069 {
00070 struct dir_buf *d;
00071 struct stat sb;
00072 d = malloc(sizeof(*d));
00073 if (d == NULL) {
00074 errno = ENOMEM;
00075 return NULL;
00076 }
00077 d->fd = open(dname, O_RDONLY);
00078 if (d->fd == -1) {
00079 free(d);
00080 return NULL;
00081 }
00082 if (fstat(d->fd, &sb) < 0) {
00083 close(d->fd);
00084 free(d);
00085 return NULL;
00086 }
00087 if (!S_ISDIR(sb.st_mode)) {
00088 close(d->fd);
00089 free(d);
00090 errno = ENOTDIR;
00091 return NULL;
00092 }
00093 d->ofs = 0;
00094 d->seekpos = 0;
00095 d->nbytes = 0;
00096 return (DIR *)d;
00097 }
00098
00099 struct dirent *readdir(DIR *dir)
00100 {
00101 struct dir_buf *d = (struct dir_buf *)dir;
00102 struct dirent *de;
00103
00104 if (d->ofs >= d->nbytes) {
00105 d->seekpos = lseek(d->fd, 0, SEEK_CUR);
00106 d->nbytes = getdents(d->fd, d->buf, DIR_BUF_SIZE);
00107 d->ofs = 0;
00108 }
00109 if (d->ofs >= d->nbytes) {
00110 return NULL;
00111 }
00112 de = (struct dirent *)&d->buf[d->ofs];
00113 d->ofs += de->d_reclen;
00114 return de;
00115 }
00116
00117 long telldir(DIR *dir)
00118 {
00119 struct dir_buf *d = (struct dir_buf *)dir;
00120 if (d->ofs >= d->nbytes) {
00121 d->seekpos = lseek(d->fd, 0, SEEK_CUR);
00122 d->ofs = 0;
00123 d->nbytes = 0;
00124 }
00125
00126
00127 if (d->seekpos & (DIR_BUF_SIZE-1)) {
00128 abort();
00129 }
00130 return d->seekpos + d->ofs;
00131 }
00132
00133 void seekdir(DIR *dir, long ofs)
00134 {
00135 struct dir_buf *d = (struct dir_buf *)dir;
00136 d->seekpos = lseek(d->fd, ofs & ~(DIR_BUF_SIZE-1), SEEK_SET);
00137 d->nbytes = getdents(d->fd, d->buf, DIR_BUF_SIZE);
00138 d->ofs = 0;
00139 while (d->ofs < (ofs & (DIR_BUF_SIZE-1))) {
00140 if (readdir(dir) == NULL) break;
00141 }
00142 }
00143
00144 void rewinddir(DIR *dir)
00145 {
00146 seekdir(dir, 0);
00147 }
00148
00149 int closedir(DIR *dir)
00150 {
00151 struct dir_buf *d = (struct dir_buf *)dir;
00152 int r = close(d->fd);
00153 if (r != 0) {
00154 return r;
00155 }
00156 free(d);
00157 return 0;
00158 }
00159
00160 #ifndef dirfd
00161
00162 int dirfd(DIR *dir)
00163 {
00164 struct dir_buf *d = (struct dir_buf *)dir;
00165 return d->fd;
00166 }
00167 #endif