ref: fd731d3c833d9241fdff618b6c949453fb5c0f31
dir: /dirent.c/
#include <dirent.h> struct DIR { Dir *d; struct dirent de; int fd; long n; /* number of entries in d */ long i; /* current entry to return from readdir */ }; struct dirent * readdir(DIR *d) { if(d->i >= d->n){ free(d->d); if((d->n = dirread(d->fd, &d->d)) <= 0) return nil; d->i = 0; } d->de.d_type = (d->d[d->i].qid.type & QTDIR) ? DT_DIR : DT_FILE; d->de.d_name = d->d[d->i].name; d->i++; return &d->de; } DIR * opendir(char *name) { Dir *dir; DIR *d; int fd; dir = nil; d = nil; if((fd = open(name, OREAD|OCEXEC)) >= 0 && (dir = dirfstat(fd)) != nil && (dir->qid.type & QTDIR) != 0 && (d = calloc(1, sizeof(*d))) != nil){ d->fd = fd; } free(dir); if(d == nil) close(fd); return d; } int closedir(DIR *d) { free(d->d); close(d->fd); free(d); return 0; }