lib: c: io: implement standard FILE and DIR interfaces

This commit is contained in:
2026-03-25 20:21:12 +00:00
parent b975256cb9
commit 96784f611f
21 changed files with 599 additions and 0 deletions
+76
View File
@@ -0,0 +1,76 @@
#include "file.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define DEFAULT_BUFFER_SIZE 4096
#define FILE_UNUSABLE(f) (((f)->f_flags & (FILE_EOF | FILE_ERR)) != 0)
int __libc_file_refill(struct __opaque_file *f)
{
f->f_buf_datalen = 0;
f->f_buf_readptr = 0;
if (f->f_fd < 0) {
return EBADF;
}
if (f->f_flags & FILE_ERR) {
return EIO;
}
if (f->f_flags & FILE_EOF) {
return SUCCESS;
}
if (!f->f_buf) {
f->f_buf_max = DEFAULT_BUFFER_SIZE;
f->f_buf = malloc(f->f_buf_max);
if (!f->f_buf) {
f->f_buf_max = 0;
return ENOMEM;
}
}
long r = read(f->f_fd, f->f_buf, f->f_buf_max);
if (r < 0) {
return -r;
}
f->f_buf_datalen = r;
return SUCCESS;
}
int __libc_file_read(struct __opaque_file *f, void *out, size_t count)
{
if (f->f_fd < 0) {
return EBADF;
}
if (f->f_flags & FILE_ERR) {
return EIO;
}
if (f->f_flags & FILE_EOF) {
return SUCCESS;
}
size_t available = f->f_buf_datalen - f->f_buf_readptr;
if (count > available) {
count = available;
}
memcpy(out, f->f_buf + f->f_buf_readptr, count);
f->f_buf_readptr += count;
return count;
}
size_t __libc_file_available(struct __opaque_file *f)
{
return f->f_buf_datalen - f->f_buf_readptr;
}