From 7bb5157581422aa63e50cea38e526fbb2ef56a6e Mon Sep 17 00:00:00 2001 From: ubq323 Date: Sat, 17 Aug 2024 19:13:54 +0100 Subject: readstring function --- lib.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/lib.c b/lib.c index 9660003..137b1bd 100644 --- a/lib.c +++ b/lib.c @@ -40,7 +40,19 @@ static Val fn_writebytes(State *S, int nargs, Val *args) { return VAL_NIL; } - +static Val fn_readstring(State *S, int nargs, Val *args){ + CHECK(nargs == 1, "need exactly 1 arg to readstring"); + CHECK(IS_STRING(args[0]), "need string arg to readstring"); + FILE *f = fopen(AS_CSTRING(args[0]), "r"); + CHECK(f != NULL, "io error (fopen)"); + fseek(f, 0L, SEEK_END); + long flen = ftell(f); + char *buf = NEW_ARR(S, char, flen+1); + rewind(f); fread(buf, 1, flen, f); + CHECK(!ferror(f), "file error"); + buf[flen] = '\0'; + return VAL_OBJ(objstring_take(S, buf, flen)); +} // lists @@ -158,6 +170,7 @@ static BuiltinFunc builtin_funcs[] = { { "say", fn_say }, { "write", fn_write }, { "writebytes", fn_writebytes }, + { "readstring", fn_readstring }, { "arr", fn_arr }, { "append!", fn_append }, -- cgit v1.2.3