commit 4c84d0bba7e0d2be09acec91380d6e489def906d
parent ae8bf534c89826cd4f67b2361a7e0f9d1fa0dcf0
Author: Francesco Saccone <francesco@francescosaccone.com>
Date: Mon, 31 Mar 2025 17:55:07 +0200
feat: define get_file_content function
Signed-off-by: Francesco Saccone <francesco@francescosaccone.com>
Diffstat:
M | file.c | | | 34 | ++++++++++++++++++++++++++++++++++ |
M | file.h | | | 7 | +++++++ |
2 files changed, 41 insertions(+), 0 deletions(-)
diff --git a/file.c b/file.c
@@ -1,5 +1,6 @@
#include "file.h"
+#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
@@ -39,3 +40,36 @@ get_normalised_path(char *path) {
return normalised;
}
+
+char *
+get_file_content(char *path) {
+ FILE *file = fopen(path, "rb");
+ long file_size;
+ char *buffer;
+ size_t bytes_read;
+
+ if (file == NULL) {
+ return NULL;
+ }
+
+ /* Move the file pointer to the end of the file */
+ fseek(file, 0, SEEK_END);
+ /* Get the size */
+ file_size = ftell(file);
+ /* Come back at the start of the file */
+ fseek(file, 0, SEEK_SET);
+
+ buffer = malloc(file_size + 1);
+
+ if (!buffer) {
+ fclose(file);
+ return NULL;
+ }
+
+ bytes_read = fread(buffer, 1, file_size, file);
+ buffer[bytes_read] = '\0';
+
+ fclose(file);
+
+ return buffer;
+}
diff --git a/file.h b/file.h
@@ -7,4 +7,11 @@ is_file_readable(char *path);
char *
get_normalised_path(char *path);
+/*
+ * Returns NULL in case of an error and a buffer containing the content of the
+ * file at the given path otherwise..
+ */
+char *
+get_file_content(char *path);
+
#endif