]> git.lizzy.rs Git - uwu-nolambda.git/blob - fs.c
Fix typo in README.md
[uwu-nolambda.git] / fs.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <string.h>
4 #include "common/err.h"
5 #include "common/file.h"
6 #include "api/vm.h"
7 #include "api/str.h"
8 #include "api/nil.h"
9 #include "api/bool.h"
10 #include "api/util.h"
11
12 UwUVMValue uwu_read(UwUVMArgs *args)
13 {
14         uwuutil_require_exact("fs.read", args, 1);
15
16         char *filename = uwustr_get(uwuvm_get_arg(args, 0));
17
18         FILE *file = fopen(filename, "r");
19         if (! file) syserror("fopen", file);
20         if (fseek(file, 0, SEEK_END) == -1) syserror("fseek", file);
21
22         size_t size = ftell(file);
23         if (size == 1) syserror("ftell", file);
24         if (fseek(file, 0, SEEK_SET) == -1) syserror("fseek", file);
25
26         char contents[size + 1];
27         if (fread(contents, 1, size, file) != size) syserror("fread", file);
28
29         fclose(file);
30         free(filename);
31
32         contents[size] = '\0';
33
34         return uwustr_create(contents);
35 }
36
37 UwUVMValue uwu_write(UwUVMArgs *args)
38 {
39         uwuutil_require_exact("fs.write", args, 2);
40         
41         char *filename = uwustr_get(uwuvm_get_arg(args, 0));
42         char *contents = uwustr_get(uwuvm_get_arg(args, 1));
43         
44         FILE *file = fopen(filename, "w");
45         if (! file) syserror("fopen", file);
46
47         size_t size = strlen(contents);
48         if (fwrite(contents, 1, size, file) != size) syserror("fwrite", file);
49
50         fclose(file);
51         free(filename);
52         free(contents);
53
54         return uwunil_create();
55 }
56
57 UwUVMValue uwu_remove(UwUVMArgs *args)
58 {
59         uwuutil_require_min("fs.remove", args, 1);
60
61         for (size_t i = 0; i < args->num; i++) {
62                 char *filename = uwustr_get(uwuvm_get_arg(args, i));
63
64                 if (remove(filename) != 0) syserror("remove", NULL);
65
66                 free(filename);
67         }
68
69         return uwunil_create();
70 }
71
72 UwUVMValue uwu_exists(UwUVMArgs *args)
73 {
74         uwuutil_require_min("fs.exists", args, 1);
75
76         for (size_t i = 0; i < args->num; i++) {
77                 char *filename = uwustr_get(uwuvm_get_arg(args, i));
78                 bool exists = file_exists(filename);
79                 free(filename);
80
81                 if (! exists)
82                         return uwubool_create(false);
83         }
84
85         return uwubool_create(true);
86 }