From 6fa4569a644090e04ff4dd1ae536c4d2b776668b Mon Sep 17 00:00:00 2001 From: Kimplul Date: Thu, 13 Aug 2026 20:15:01 +0300 Subject: allow reading from file --- src/fwdscript.c | 56 ++++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 48 insertions(+), 8 deletions(-) (limited to 'src/fwdscript.c') diff --git a/src/fwdscript.c b/src/fwdscript.c index 6b47ca0..7b1de26 100644 --- a/src/fwdscript.c +++ b/src/fwdscript.c @@ -1,9 +1,11 @@ #include #include #include +#include #include #include #include +#include #define TODO() errx(EXIT_FAILURE, "%s:%d: todo", __FILE__, __LINE__) @@ -1521,21 +1523,56 @@ static void fwdscript_destroy(struct fwdscript *s) fwdbuiltins_destroy(&s->builtins); } -int main() +static const char *read_file(const char *fname) { + FILE *f = fopen(fname, "rb"); + if (!f) + err(EXIT_FAILURE, "failed opening %s", fname); + + if (fseek(f, 0, SEEK_END) < 0) + err(EXIT_FAILURE, "failed seeking %s", fname); + + long sz = ftell(f); + if (sz < 0) + err(EXIT_FAILURE, "failed telling %s", fname); + + if (fseek(f, 0, SEEK_SET) < 0) + err(EXIT_FAILURE, "failed rewinding %s", fname); + + char *buf = malloc(sz + 1); + if (!buf) + err(EXIT_FAILURE, "failed allocating buf for %s", fname); + + if ((long)fread(buf, 1, sz, f) != sz) + err(EXIT_FAILURE, "failed reading file %s", fname); + + /* trailing zero */ + buf[sz] = '\0'; + + fclose(f); + return buf; +} + +int main(int argc, char *argv[]) +{ + /* a bit silly but good enough for testing */ + const char *buf = + "main /tbl args {\n" + " get args 0 => {abort \"impossible\"}\n" + " => /str line;\n" + " print line\n" + "}\n"; + + if (argc == 2) + buf = read_file(argv[1]); + int ret = 0; struct fwdscript inst = fwdscript_create(); ret = fwdscript_register_builtins(&inst); assert(ret == 0); - ret = fwdscript_parse(&inst, - "main /tbl args {\n" - " get args 0 => {abort \"impossible\"}\n" - " => /str line;\n" - " print line\n" - "}\n"); - + ret = fwdscript_parse(&inst, buf); assert(ret == 0); struct fwdvals args = fwdvals_create(1); @@ -1546,4 +1583,7 @@ int main() /* string should've been consumed by main so we shouldn't try to free it */ fwdvals_destroy(&args); fwdscript_destroy(&inst); + + if (argc == 2) + free((void *)buf); } -- cgit v1.3