summaryrefslogtreecommitdiff
path: root/lib.c
diff options
context:
space:
mode:
Diffstat (limited to 'lib.c')
-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 },