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
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
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 * path
Definition download.c:43
FunCurlBuf buf
Definition get.c:48
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
static Value pop_value(VM *vm)
Pop a Value from the VM operand stack.
Definition vm.c:580
#define fprintf
Definition vm.c:200
#define exit(code)
Definition vm.c:230