diff options
author | mrb0nk500 <b0nk@b0nk.xyz> | 2021-06-18 09:38:10 -0400 |
---|---|---|
committer | mrb0nk500 <b0nk@b0nk.xyz> | 2021-06-18 09:38:10 -0400 |
commit | 8c7006c3ce636e7ba4127e5567350c334c3ea5e1 (patch) | |
tree | 4a05f4df6cea2a8d4cf43e130dfeee23ea9ec3b1 | |
parent | dc9f35b35a7d7fd6e831f3ee287d1e7ad96e684e (diff) |
Move all miscellaneous functions from `config.c` into
`misc.c`.
-rw-r--r-- | config.c | 1 | ||||
-rw-r--r-- | misc.c | 75 | ||||
-rw-r--r-- | misc.h | 7 |
3 files changed, 83 insertions, 0 deletions
@@ -5,6 +5,7 @@ #include <syslog.h> #include "config.h" #include "macros.h" +#include "misc.h" char *read_file(const char *filename, long *size) { /* Open the file. */ @@ -0,0 +1,75 @@ +#include <string.h> +#include <stdio.h> +#include <stdlib.h> +#include "misc.h" + +char *read_file(const char *filename, long *size) { + /* Open the file. */ + FILE *fp = fopen(filename, "r"); + /* Size of the file, in bytes. */ + long filesize = 0; + /* Buffer of the file contents. */ + char *buf; + + /* Return NULL, if we couldn't open the file. */ + if (fp == NULL) { + return NULL; + } + + /* Return NULL, if we couldn't seek to the end of the file. */ + if (fseek(fp, 0L, SEEK_END)) { + fclose(fp); + return NULL; + } + + /* Get the size of the file, in bytes. */ + filesize = ftell(fp); + + /* Return NULL, if the returned size is negative. */ + if (filesize < 0) { + fclose(fp); + return NULL; + } + + /* Allocate enough space for the entire file, plus one. */ + buf = calloc(filesize+1, sizeof(char)); + + /* Return NULL, if the buffer wasn't allocated. */ + if (buf == NULL) { + fclose(fp); + return NULL; + } + + /* Seek back to the start of the file. */ + rewind(fp); + /* Read the entire file contents into the buffer. */ + fread(buf, sizeof(char), filesize, fp); + /* Close the file. */ + fclose(fp); + + /* Return the filesize, in bytes. */ + *size = filesize; + /* Return the buffer. */ + return buf; +} + +char *get_line(char **str) { + char *s; + size_t i; + char *tmp = *str; + + for (i = 0; tmp[i] != '\n' && tmp[i] != '\0'; i++); + + s = calloc(i+1, sizeof(char)); + memcpy(s, *str, i); + + *str += (i+1); + return s; +} + +char *make_str(const char *str) { + const size_t length = strlen(str); + char *s = calloc(length+1, sizeof(char)); + memcpy(s, str, length+1); + return s; +} @@ -0,0 +1,7 @@ +#ifndef MISC_H +#define MISC_H + +extern char *read_file(const char *filename, long *size); +extern char *get_line(char **str); +extern char *make_str(const char *str); +#endif |