hermes

HTTP GET/HEAD-only web server for static content.
git clone git://git.francescosaccone.com/hermes
Log | Files | Refs | README | LICENSE

commit 81d386286ceeaf2f4a031ae4b0fb456bb1cfab5f
parent 588063dc0d636b07a747ce8dbac6021e1f055a9f
Author: Francesco Saccone <francesco@francescosaccone.com>
Date:   Mon, 31 Mar 2025 18:03:58 +0200

feat: make get_file_content return struct file_content

Signed-off-by: Francesco Saccone <francesco@francescosaccone.com>

Diffstat:
Mfile.c | 21++++++++++++---------
Mfile.h | 10+++++++---
2 files changed, 19 insertions(+), 12 deletions(-)

diff --git a/file.c b/file.c @@ -41,15 +41,15 @@ get_normalised_path(char *path) { return normalised; } -char * +struct file_content get_file_content(char *path) { + struct file_content result = { NULL, 0 }; FILE *file = fopen(path, "rb"); long file_size; - char *buffer; size_t bytes_read; if (file == NULL) { - return NULL; + return result; } /* Move the file pointer to the end of the file */ @@ -59,17 +59,20 @@ get_file_content(char *path) { /* Come back at the start of the file */ fseek(file, 0, SEEK_SET); - buffer = malloc(file_size + 1); + result.content = malloc(file_size + 1); - if (!buffer) { + if (!result.content) { fclose(file); - return NULL; + return result; } - bytes_read = fread(buffer, 1, file_size, file); - buffer[bytes_read] = '\0'; + bytes_read = fread(result.content, 1, file_size, file); + + /* 'result' gets written here. Before this, it remained { NULL, 0 }. */ + result.content[bytes_read] = '\0'; + result.length = bytes_read; fclose(file); - return buffer; + return result; } diff --git a/file.h b/file.h @@ -1,6 +1,8 @@ #ifndef FILE_H #define FILE_H +#include <stdlib.h> + struct file_content { char *content; size_t length; @@ -13,10 +15,12 @@ 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.. + * It returns the file_content instances of the file at given path. + * + * Returns 'struct file_content { NULL, 0 }' in case of an error and a + * non-empty file_content instance otherwise. */ -char * +struct file_content get_file_content(char *path); #endif