Fun 0.41.5
The programming language that makes You have fun
Loading...
Searching...
No Matches
read_file.c
Go to the documentation of this file.
1/*
2 * This file is part of the Fun programming language.
3 * https://fun-lang.xyz/
4 *
5 * Copyright 2025 Johannes Findeisen <you@hanez.org>
6 * Licensed under the terms of the Apache-2.0 license.
7 * https://opensource.org/license/apache-2-0
8 */
9
30
32 Value path = pop_value(vm);
33 if (path.type != VAL_STRING) {
34 fprintf(stderr, "READ_FILE expects string\n");
35 exit(1);
36 }
37 const char *p = path.s ? path.s : "";
38 FILE *f = fopen(p, "rb");
39 if (!f) {
41 push_value(vm, make_string(""));
42 break;
43 }
44 if (fseek(f, 0, SEEK_END) != 0) {
45 fclose(f);
47 push_value(vm, make_string(""));
48 break;
49 }
50 long sz = ftell(f);
51 if (sz < 0) {
52 fclose(f);
54 push_value(vm, make_string(""));
55 break;
56 }
58 char *buf = (char *)malloc((size_t)sz + 1);
59 size_t n = buf ? fread(buf, 1, (size_t)sz, f) : 0;
61 if (!buf) {
63 push_value(vm, make_string(""));
64 break;
65 }
66 buf[n] = '\0';
71 break;
72}
Value out
Definition apop.c:38
@ OP_READ_FILE
Definition bytecode.h:136
char * buf
Definition input_line.c:103
int n
Definition insert.c:41
rewind(f)
fclose(f)
FILE * f
Definition read_file.c:38
const char * p
Definition read_file.c:37
long sz
Definition read_file.c:50
push_value(vm, out)
free(buf)
free_value(path)
Tagged union representing a Fun value.
Definition value.h:68
Value make_string(const char *s)
Construct a string Value by duplicating the given C string.
Definition value.c:95
@ VAL_STRING
Definition value.h:53
#define fprintf
Definition vm.c:200
#define exit(code)
Definition vm.c:230
Value path
Definition write_file.c:33