]> git.lizzy.rs Git - uwu-nolambda.git/blob - fs.c
Implement nolambda:fs module
[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("nolambda: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];
27         if (fread(contents, 1, size, file) != size) syserror("fread", file);
28
29         fclose(file);
30         free(filename);
31
32         return uwustr_create(contents);
33 }
34
35 UwUVMValue uwu_write(UwUVMArgs *args)
36 {
37         uwuutil_require_exact("nolambda:fs:write", args, 2);
38         
39         char *filename = uwustr_get(uwuvm_get_arg(args, 0));
40         char *contents = uwustr_get(uwuvm_get_arg(args, 1));
41         
42         FILE *file = fopen(filename, "w");
43         if (! file) syserror("fopen", file);
44
45         size_t size = strlen(contents);
46         if (fwrite(contents, 1, size, file) != size) syserror("fwrite", file);
47
48         fclose(file);
49         free(filename);
50         free(contents);
51
52         return uwunil_create();
53 }
54
55 UwUVMValue uwu_remove(UwUVMArgs *args)
56 {
57         uwuutil_require_min("nolambda:fs:remove", args, 1);
58
59         for (size_t i = 0; i < args->num; i++) {
60                 char *filename = uwustr_get(uwuvm_get_arg(args, i));
61
62                 if (remove(filename) != 0) syserror("remove", NULL);
63
64                 free(filename);
65         }
66
67         return uwunil_create();
68 }
69
70 UwUVMValue uwu_exists(UwUVMArgs *args)
71 {
72         uwuutil_require_min("nolambda:fs:exists", args, 1);
73
74         for (size_t i = 0; i < args->num; i++) {
75                 char *filename = uwustr_get(uwuvm_get_arg(args, i));
76                 bool exists = file_exists(filename);
77                 free(filename);
78
79                 if (! exists)
80                         return uwubool_create(false);
81         }
82
83         return uwubool_create(true);
84 }