common: add generic input-line interface, and an implementation of it for text files

This commit is contained in:
2024-11-13 21:36:37 +00:00
parent bf2c9c1d90
commit cbd8639605
6 changed files with 96 additions and 11 deletions

42
common/file.c Normal file
View File

@@ -0,0 +1,42 @@
#include <ivy/file.h>
#include <stdlib.h>
#include <string.h>
static enum ivy_status file_readline(
struct ivy_line_source *src, char *buf, size_t count, size_t *nr_read,
const char *prompt)
{
if (!count) {
*nr_read = 0;
return IVY_OK;
}
struct ivy_file *f = (struct ivy_file *)src;
if (!fgets(buf, count, f->f_fp)) {
return feof(f->f_fp) ? IVY_ERR_EOF : IVY_ERR_IO_FAILURE;
}
*nr_read = strlen(buf);
return IVY_OK;
}
struct ivy_file *ivy_file_from_fp(FILE *fp)
{
struct ivy_file *file = malloc(sizeof *file);
if (!file) {
return NULL;
}
memset(file, 0x0, sizeof *file);
file->f_fp = fp;
file->f_base.s_readline = file_readline;
return file;
}
void ivy_file_close(struct ivy_file *file)
{
fclose(file->f_fp);
free(file);
}