summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorkdx <kdx@42l.fr>2023-03-14 00:25:11 +0100
committerkdx <kdx@42l.fr>2023-03-14 00:28:27 +0100
commit94381fd0fdaed4030b5d6661ad7d342fc4994847 (patch)
treee0bd9748aa753001a17b90d896d57b60b3612c5b
parent456885959512aeb86d5141843febd24d40a59969 (diff)
downloadgolem-94381fd0fdaed4030b5d6661ad7d342fc4994847.tar.gz
drain input file
-rw-r--r--drain.c30
-rw-r--r--drain.h6
-rw-r--r--main.c24
-rw-r--r--slice.c2
-rw-r--r--slice.h4
-rwxr-xr-xtest.sh1
6 files changed, 60 insertions, 7 deletions
diff --git a/drain.c b/drain.c
new file mode 100644
index 0000000..ae403e7
--- /dev/null
+++ b/drain.c
@@ -0,0 +1,30 @@
+#include "drain.h"
+#include <stdio.h>
+#include <stdlib.h>
+
+char *
+drain(FILE *fp)
+{
+ if (fseek(fp, 0, SEEK_END) < 0) {
+ perror("drain:SEEK_END");
+ return NULL;
+ }
+ long size = ftell(fp);
+ if (fseek(fp, 0, SEEK_SET) < 0) {
+ perror("drain:SEEK_SET");
+ return NULL;
+ }
+ char *data = malloc(size + 1);
+ if (data == NULL) {
+ perror("drain:malloc");
+ return NULL;
+ }
+ if ((long)fread(data, 1, size, fp) != size) {
+ perror("drain:fread");
+ free(data);
+ return NULL;
+ }
+ data[size] = '\0';
+ return data;
+}
+
diff --git a/drain.h b/drain.h
new file mode 100644
index 0000000..7ad6b9c
--- /dev/null
+++ b/drain.h
@@ -0,0 +1,6 @@
+#pragma once
+#include <stdio.h>
+
+// IO helper. Read the entirety of a FILE* content into a freshly alloced array.
+// Returns NULL on error.
+char *drain(FILE *fp);
diff --git a/main.c b/main.c
index a881c87..5862053 100644
--- a/main.c
+++ b/main.c
@@ -1,11 +1,27 @@
#include "slice.h"
+#include "drain.h"
+#include <stdio.h>
+#include <stdlib.h>
int
-main(void)
+main(int argc, char **argv)
{
- Slice slice = slice_from_str("bonsoir paris");
+ if (argc != 2) {
+ fprintf(stderr, "usage: %s <source.golem>\n", argv[0]);
+ return 1;
+ }
+
+ FILE *file = fopen(argv[1], "rb");
+ if (file == NULL) {
+ perror("main:fopen");
+ return 1;
+ }
+
+ Slice slice = slice_from_str(drain(file));
+ fclose(file);
slice_print(slice);
- slice_print(slice_sub(slice, 3, 4));
- slice_print(slice_sub(slice, 3, 7));
+ if (slice.str != NULL)
+ free(slice.str);
+
return 0;
}
diff --git a/slice.c b/slice.c
index 172da58..dba8086 100644
--- a/slice.c
+++ b/slice.c
@@ -15,7 +15,7 @@ slice_print(Slice slice)
}
Slice
-slice_from_str(const char *str)
+slice_from_str(char *str)
{
if (str == NULL)
return (Slice){ NULL, 0, 0 };
diff --git a/slice.h b/slice.h
index b15bb54..9669132 100644
--- a/slice.h
+++ b/slice.h
@@ -1,11 +1,11 @@
#pragma once
typedef struct {
- const char *str;
+ char *str;
int begin;
int end;
} Slice;
Slice slice_print(Slice slice);
-Slice slice_from_str(const char *str);
+Slice slice_from_str(char *str);
Slice slice_sub(Slice src, int begin, int end);
diff --git a/test.sh b/test.sh
index 12c4ba3..9e8fd3b 100755
--- a/test.sh
+++ b/test.sh
@@ -1,3 +1,4 @@
#!/bin/sh
./build.sh || exit 1
./golem mvp.golem || exit 1
+valgrind ./golem mvp.golem || exit 1