summaryrefslogtreecommitdiff
path: root/tests/slurp.c
diff options
context:
space:
mode:
authorEuAndreh <eu@euandre.org>2024-04-07 11:49:25 -0300
committerEuAndreh <eu@euandre.org>2024-04-07 11:49:25 -0300
commit381492a000454822398a8737c73ea586464ee56a (patch)
tree9e28124ba2373b157356f0d5172b60009a20041e /tests/slurp.c
parentsrc/lib.c: Print project metadata on pindaiba_main (diff)
downloadpindaiba-381492a000454822398a8737c73ea586464ee56a.tar.gz
pindaiba-381492a000454822398a8737c73ea586464ee56a.tar.xz
src/util.c: Add slurp(), with a simple test
Diffstat (limited to 'tests/slurp.c')
-rw-r--r--tests/slurp.c37
1 files changed, 22 insertions, 15 deletions
diff --git a/tests/slurp.c b/tests/slurp.c
index 6ea8618..6b6a02e 100644
--- a/tests/slurp.c
+++ b/tests/slurp.c
@@ -1,20 +1,25 @@
#include "../src/config.h"
+#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include "slurp.h"
+
+static const size_t
+NULL_TERMINATOR = sizeof((char)'\0');
+
int
-slurp_for_tests(const char *const FNAME, char **strref) {
+slurp_for_tests(const char *const filename, char **out) {
int rc = -1;
FILE *file = NULL;
- char *str = NULL;
+ char *str = NULL;
- file = fopen(FNAME, "r");
- if (!file) {
- perror("fopen(FNAME, \"r\")");
+ file = fopen(filename, "r");
+ if (file == NULL) {
+ perror("fopen(filename, \"r\")");
goto out;
}
@@ -28,29 +33,31 @@ slurp_for_tests(const char *const FNAME, char **strref) {
perror("ftell(file)");
goto out;
}
- const size_t size = (size_t)lsize + sizeof(char);
+ const size_t size = (size_t)lsize;
- if (fseek(file, 0L, SEEK_SET)) {
- perror("fseek(file, 0L, SEEK_SET)");
+ errno = 0;
+ rewind(file);
+ if (errno) {
+ perror("rewind(file)");
goto out;
}
- str = malloc(size);
- if (!str) {
+ str = malloc(size + NULL_TERMINATOR);
+ if (str == NULL) {
perror("malloc(...)");
goto out;
}
- if (fread(str, sizeof(char), size - 1, file) != size - 1) {
+ if (fread(str, sizeof(char), size, file) != size) {
perror("fread(...)");
goto out;
}
- str[size - 1] = '\0';
- *strref = str;
+ str[size] = '\0';
+ *out = str;
rc = 0;
out:
- if (file) {
+ if (file != NULL) {
if (fclose(file)) {
perror("flcose(file");
rc = -1;
@@ -58,7 +65,7 @@ out:
}
if (rc) {
- if (str) {
+ if (str != NULL) {
free(str);
}
}