summaryrefslogtreecommitdiffstats
path: root/io.c
diff options
context:
space:
mode:
authorSam Anthony <sam@samanthony.xyz>2024-11-13 12:14:12 -0500
committerSam Anthony <sam@samanthony.xyz>2024-11-13 12:14:12 -0500
commit44792fd5369cfe2ad1478b72bf22b0d1829f291b (patch)
treeee991768c1632b50eaaba6e6b4f873eae420871a /io.c
parent2e442c894d50c42aea748d21a6f08add123e9a70 (diff)
downloadballs-44792fd5369cfe2ad1478b72bf22b0d1829f291b.zip
move readFile() out of balls.c
Diffstat (limited to 'io.c')
-rw-r--r--io.c32
1 files changed, 32 insertions, 0 deletions
diff --git a/io.c b/io.c
new file mode 100644
index 0000000..dbd12f4
--- /dev/null
+++ b/io.c
@@ -0,0 +1,32 @@
+#include <stdlib.h>
+#include <stdio.h>
+
+#include "balls.h"
+#include "sysfatal.h"
+
+/*
+ * Read the file called filename. Sets contents to a malloc-allocated string containing
+ * the contents of the file and a terminal '\0'. Sets size to strlen(contents) (excludes
+ * '\0'). Returns non-zero on error.
+ */
+int
+readFile(const char *filename, char **contents, size_t *size) {
+ FILE *f;
+
+ if ((f = fopen(filename, "r")) == NULL) {
+ fprintf(stderr, "Failed to open file '%s'\n", filename);
+ return 1;
+ }
+ fseek(f, 0, SEEK_END);
+ *size = ftell(f);
+ if ((*contents = malloc((*size + 1) * sizeof(char))) == NULL) {
+ fclose(f);
+ fprintf(stderr, "Failed to allocate file buffer for '%s'\n", filename);
+ return 1;
+ }
+ rewind(f);
+ fread(*contents, sizeof(char), *size, f);
+ (*contents)[*size] = '\0';
+ fclose(f);
+ return 0;
+}