77 lines
1.2 KiB
C
77 lines
1.2 KiB
C
|
|
#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;
|
||
|
|
}
|