diff options
author | kdx <kdx@42l.fr> | 2023-03-14 00:25:11 +0100 |
---|---|---|
committer | kdx <kdx@42l.fr> | 2023-03-14 00:28:27 +0100 |
commit | 94381fd0fdaed4030b5d6661ad7d342fc4994847 (patch) | |
tree | e0bd9748aa753001a17b90d896d57b60b3612c5b | |
parent | 456885959512aeb86d5141843febd24d40a59969 (diff) | |
download | golem-94381fd0fdaed4030b5d6661ad7d342fc4994847.tar.gz |
drain input file
-rw-r--r-- | drain.c | 30 | ||||
-rw-r--r-- | drain.h | 6 | ||||
-rw-r--r-- | main.c | 24 | ||||
-rw-r--r-- | slice.c | 2 | ||||
-rw-r--r-- | slice.h | 4 | ||||
-rwxr-xr-x | test.sh | 1 |
6 files changed, 60 insertions, 7 deletions
@@ -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; +} + @@ -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); @@ -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; } @@ -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 }; @@ -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); @@ -1,3 +1,4 @@ #!/bin/sh ./build.sh || exit 1 ./golem mvp.golem || exit 1 +valgrind ./golem mvp.golem || exit 1 |