toaruos/libc/dirent/dir.c

47 lines
800 B
C
Raw Normal View History

2018-02-25 08:13:54 +03:00
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <syscall.h>
2018-07-18 04:45:42 +03:00
#include <errno.h>
2018-02-25 08:13:54 +03:00
#include <bits/dirent.h>
DIR * opendir (const char * dirname) {
int fd = open(dirname, O_RDONLY);
2018-07-18 04:45:42 +03:00
if (fd < 0) {
errno = -fd;
2018-02-25 08:13:54 +03:00
return NULL;
}
DIR * dir = (DIR *)malloc(sizeof(DIR));
dir->fd = fd;
dir->cur_entry = -1;
return dir;
}
int closedir (DIR * dir) {
if (dir && (dir->fd != -1)) {
return close(dir->fd);
} else {
2018-07-18 04:45:42 +03:00
return -EBADF;
2018-02-25 08:13:54 +03:00
}
}
struct dirent * readdir (DIR * dirp) {
static struct dirent ent;
int ret = syscall_readdir(dirp->fd, ++dirp->cur_entry, &ent);
2018-07-18 04:45:42 +03:00
if (ret < 0) {
errno = -ret;
memset(&ent, 0, sizeof(struct dirent));
return NULL;
}
if (ret == 0) {
/* end of directory */
2018-02-25 08:13:54 +03:00
memset(&ent, 0, sizeof(struct dirent));
return NULL;
}
return &ent;
}