summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorubq323 <ubq323@ubq323.website>2024-08-17 19:13:54 +0100
committerubq323 <ubq323@ubq323.website>2024-08-17 19:13:54 +0100
commit7bb5157581422aa63e50cea38e526fbb2ef56a6e (patch)
treec94d13af147ed0668130cedb58b99ef3acebad7c
parentf0f04d875ec1db53371331774c0db9a11b072f19 (diff)
readstring function
-rw-r--r--lib.c15
1 files changed, 14 insertions, 1 deletions
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 },