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
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
buf
char * buf
Definition
input_line.c:103
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
fprintf
#define fprintf
Definition
vm.c:200
exit
#define exit(code)
Definition
vm.c:230
path
Value path
Definition
write_file.c:33
Generated on
for Fun by
1.16.1