Fun
0.41.5
The programming language that makes you have fun!
Main Page
Data Structures
Files
File List
Globals
Loading...
Searching...
No Matches
src
vm
io
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
10
/**
11
* @file read_file.c
12
* @brief Implements the OP_READ_FILE opcode for reading file contents in the VM.
13
*
14
* This file handles the OP_READ_FILE instruction, which reads the contents of a file
15
* and pushes the result as a string onto the stack.
16
*
17
* Behavior:
18
* - Pops the file path from the stack.
19
* - Reads the file contents.
20
* - Pushes the contents as a string onto the stack.
21
*
22
* Error Handling:
23
* - Exits with an error if the file path is invalid or the file cannot be read.
24
*
25
* Example:
26
* - Bytecode: OP_READ_FILE
27
* - Stack before: ["file.txt"]
28
* - Stack after: ["file contents"]
29
*/
30
31
case
OP_READ_FILE
: {
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
) {
40
free_value
(
path
);
41
push_value
(vm,
make_string
(
""
));
42
break
;
43
}
44
if
(fseek(
f
, 0, SEEK_END) != 0) {
45
fclose
(
f
);
46
free_value
(
path
);
47
push_value
(vm,
make_string
(
""
));
48
break
;
49
}
50
long
sz
= ftell(
f
);
51
if
(
sz
< 0) {
52
fclose
(
f
);
53
free_value
(
path
);
54
push_value
(vm,
make_string
(
""
));
55
break
;
56
}
57
rewind
(
f
);
58
char
*
buf
= (
char
*)malloc((
size_t
)
sz
+ 1);
59
size_t
n
=
buf
? fread(
buf
, 1, (
size_t
)
sz
,
f
) : 0;
60
fclose
(
f
);
61
if
(!
buf
) {
62
free_value
(
path
);
63
push_value
(vm,
make_string
(
""
));
64
break
;
65
}
66
buf
[
n
] =
'\0'
;
67
Value
out
=
make_string
(
buf
);
68
free
(
buf
);
69
free_value
(
path
);
70
push_value
(vm,
out
);
71
break
;
72
}
out
Value out
Definition
apop.c:38
OP_READ_FILE
@ OP_READ_FILE
Definition
bytecode.h:136
path
char * path
Definition
download.c:43
buf
FunCurlBuf buf
Definition
get.c:48
n
int n
Definition
insert.c:41
rewind
rewind(f)
fclose
fclose(f)
f
FILE * f
Definition
read_file.c:38
p
const char * p
Definition
read_file.c:37
sz
long sz
Definition
read_file.c:50
push_value
push_value(vm, out)
free
free(buf)
free_value
free_value(path)
Value
Tagged union representing a Fun value.
Definition
value.h:68
make_string
Value make_string(const char *s)
Construct a string Value by duplicating the given C string.
Definition
value.c:95
VAL_STRING
@ VAL_STRING
Definition
value.h:53
pop_value
static Value pop_value(VM *vm)
Pop a Value from the VM operand stack.
Definition
vm.c:580
fprintf
#define fprintf
Definition
vm.c:200
exit
#define exit(code)
Definition
vm.c:230
Generated on
for Fun by
1.16.1