2023-06-11 00:19:20 +03:00
|
|
|
#include <dirent.h>
|
|
|
|
#include <errno.h>
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <sys/syscall.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
|
|
|
|
struct __DIR
|
|
|
|
{
|
|
|
|
int fd { -1 };
|
2024-05-22 20:17:39 +03:00
|
|
|
size_t entry_count { 0 };
|
2023-06-11 00:19:20 +03:00
|
|
|
size_t entry_index { 0 };
|
2024-05-22 20:17:39 +03:00
|
|
|
// FIXME: we should probably allocate entries dynamically
|
|
|
|
// based if syscall returns ENOBUFS
|
|
|
|
dirent entries[128];
|
2023-06-11 00:19:20 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
int closedir(DIR* dirp)
|
|
|
|
{
|
|
|
|
if (dirp == nullptr || dirp->fd == -1)
|
|
|
|
{
|
|
|
|
errno = EBADF;
|
|
|
|
return -1;
|
|
|
|
}
|
2023-09-09 22:52:03 +03:00
|
|
|
|
2023-06-11 00:19:20 +03:00
|
|
|
close(dirp->fd);
|
|
|
|
free(dirp);
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
int dirfd(DIR* dirp)
|
|
|
|
{
|
|
|
|
if (dirp == nullptr || dirp->fd == -1)
|
|
|
|
{
|
|
|
|
errno = EINVAL;
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
return dirp->fd;
|
|
|
|
}
|
|
|
|
|
|
|
|
DIR* fdopendir(int fd)
|
|
|
|
{
|
2024-05-22 20:17:39 +03:00
|
|
|
DIR* dirp = (DIR*)malloc(sizeof(DIR));
|
2023-06-11 00:19:20 +03:00
|
|
|
if (dirp == nullptr)
|
|
|
|
return nullptr;
|
|
|
|
|
|
|
|
dirp->fd = fd;
|
2024-05-22 20:17:39 +03:00
|
|
|
dirp->entry_count = 0;
|
|
|
|
dirp->entry_index = 0;
|
2023-06-11 00:19:20 +03:00
|
|
|
|
|
|
|
return dirp;
|
|
|
|
}
|
|
|
|
|
|
|
|
DIR* opendir(const char* dirname)
|
|
|
|
{
|
2023-09-08 11:46:53 +03:00
|
|
|
int fd = open(dirname, O_RDONLY);
|
2023-06-11 00:19:20 +03:00
|
|
|
if (fd == -1)
|
|
|
|
return nullptr;
|
|
|
|
return fdopendir(fd);
|
|
|
|
}
|
|
|
|
|
|
|
|
struct dirent* readdir(DIR* dirp)
|
|
|
|
{
|
|
|
|
if (dirp == nullptr || dirp->fd == -1)
|
|
|
|
{
|
|
|
|
errno = EBADF;
|
|
|
|
return nullptr;
|
|
|
|
}
|
|
|
|
|
|
|
|
dirp->entry_index++;
|
2024-05-22 20:17:39 +03:00
|
|
|
if (dirp->entry_index < dirp->entry_count)
|
|
|
|
return &dirp->entries[dirp->entry_index];
|
2023-06-11 00:19:20 +03:00
|
|
|
|
2024-05-22 20:17:39 +03:00
|
|
|
long entry_count = syscall(SYS_READ_DIR, dirp->fd, dirp->entries, sizeof(dirp->entries) / sizeof(dirp->entries[0]));
|
|
|
|
if (entry_count <= 0)
|
2023-06-11 00:19:20 +03:00
|
|
|
return nullptr;
|
|
|
|
|
2024-05-22 20:17:39 +03:00
|
|
|
dirp->entry_count = entry_count;
|
2023-06-11 00:19:20 +03:00
|
|
|
dirp->entry_index = 0;
|
|
|
|
|
2024-05-22 20:17:39 +03:00
|
|
|
return &dirp->entries[0];
|
2023-06-11 00:19:20 +03:00
|
|
|
}
|