From beb8db73aadbd7d0464f1530ef86c961bc1aa2a0 Mon Sep 17 00:00:00 2001 From: cflip Date: Sat, 27 May 2023 12:08:00 -0600 Subject: Split cfws.c into multiple files --- file.c | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 file.c (limited to 'file.c') diff --git a/file.c b/file.c new file mode 100644 index 0000000..a8fef33 --- /dev/null +++ b/file.c @@ -0,0 +1,47 @@ +#include "file.h" + +#include +#include +#include +#include +#include +#include +#include + +size_t file_read(const char *uri_path, char **buffer) +{ + FILE *fp; + struct stat statbuf; + char path[PATH_MAX]; + long len; + + /* Prepend the current working directory to the uri path */ + getcwd(path, PATH_MAX); + strncat(path, uri_path, PATH_MAX - 1); + + /* Append 'index.html' to directory paths. */ + stat(path, &statbuf); + if (S_ISDIR(statbuf.st_mode)) + strcat(path, "index.html"); + + fp = fopen(path, "rb"); + if (fp == NULL) { + /* + * File not found is a very common and harmless error, so + * there's no need to print it out every time. + */ + if (errno != ENOENT) + perror("Failed to open file"); + return 0; + } + + fseek(fp, 0, SEEK_END); + len = ftell(fp); + fseek(fp, 0, SEEK_SET); + + *buffer = malloc(len); + fread(*buffer, 1, len, fp); + + fclose(fp); + return len; +} -- cgit v1.2.3