Fun 0.41.5
The programming language that makes you have fun!
Loading...
Searching...
No Matches
write_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 write_file.c
12 * @brief Implements the OP_WRITE_FILE opcode for writing to a file in the VM.
13 *
14 * This file handles the OP_WRITE_FILE instruction, which writes data to a file.
15 * The file path and data are popped from the stack, and a success/failure flag is pushed back.
16 *
17 * Behavior:
18 * - Pops the file path and data from the stack.
19 * - Writes the data to the file.
20 * - Pushes 1 (success) or 0 (failure) onto the stack.
21 *
22 * Error Handling:
23 * - Exits with an error if the file path is invalid or the file cannot be written.
24 *
25 * Example:
26 * - Bytecode: OP_WRITE_FILE
27 * - Stack before: ["file.txt", "data"]
28 * - Stack after: [1]
29 */
30
32 Value data = pop_value(vm);
34 if (path.type != VAL_STRING || data.type != VAL_STRING) {
35 fprintf(stderr, "WRITE_FILE expects (string, string)\n");
36 exit(1);
37 }
38 const char *p = path.s ? path.s : "";
39 FILE *f = fopen(p, "wb");
40 int ok = 0;
41 if (f) {
42 size_t len = data.s ? strlen(data.s) : 0;
43 ok = (fwrite(data.s ? data.s : "", 1, len, f) == len);
44 fclose(f);
45 }
48 push_value(vm, make_int(ok ? 1 : 0));
49 break;
50}
@ OP_WRITE_FILE
Definition bytecode.h:137
int ok
Definition contains.c:38
fclose(fp)
char * path
Definition download.c:43
size_t len
Definition input_line.c:102
FILE * f
Definition read_file.c:38
const char * p
Definition read_file.c:37
Tagged union representing a Fun value.
Definition value.h:68
ValueType type
Definition value.h:69
char * s
Definition value.h:73
Value make_int(int64_t v)
Construct a Value representing a 64-bit integer.
Definition value.c:51
@ 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
push_value(vm, make_int(ok ? 1 :0))
free_value(path)