From b2fada1dd19211d71e04557653d08e697134a6ce Mon Sep 17 00:00:00 2001 From: Erik K Date: Fri, 13 May 2022 17:24:26 +0000 Subject: initial commit --- util.c | 83 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 util.c (limited to 'util.c') diff --git a/util.c b/util.c new file mode 100644 index 0000000..3f4f51d --- /dev/null +++ b/util.c @@ -0,0 +1,83 @@ +#include +#include +#include +#include + +#include "util.h" + +/* This isn't a 1:1 wrapper around fgets. It also removes that annoying + * trailing \n automatically */ +char * +xfgets(char *s, size_t size, FILE *stream) +{ + char *p; + if ((s = fgets(s, size, stream))) { + if ((p = strchr(s, '\n'))) + *p = '\0'; + } else if (ferror(stream)) { + fprintf(stderr, "fgets: %s\n", strerror(errno)); + exit(1); + } + return s; +} + +FILE * +xfopen(const char *pathname, const char *mode) +{ + FILE *f; + if ((f = fopen(pathname, mode)) == NULL) { + fprintf(stderr, "%s: %s\n", pathname, strerror(errno)); + exit(1); + } + return f; +} + +int +xfputs(const char *s, FILE *stream) +{ + int d; + if ((d = fputs(s, stream)) == EOF) { + fprintf(stderr, "fputs: %s\n", strerror(errno)); + exit(1); + } + return d; +} + +void * +xmalloc(size_t size) +{ + void *n; + if ((n = malloc(size)) == NULL) { + fprintf(stderr, "malloc: %s\n", strerror(errno)); + exit(1); + } + return n; +} + +void * +xrealloc(void *ptr, size_t size) +{ + void *n; + if ((n = realloc(ptr, size)) == NULL) { + fprintf(stderr, "malloc: %s\n", strerror(errno)); + exit(1); + } + return n; +} + +/* strlcpy is unportable, and strncpy is a mess. So we define our own strlcpy + * instead. */ +size_t +my_strlcpy(char *dst, const char *src, size_t size) +{ + const char *p2; + char *p1, *stop; + + p1 = dst; + p2 = src; + stop = dst + size; + while (*p2 && p1 != stop) + *p1++ = *p2++; + *p1 = '\0'; + return (size_t)(p1 - dst); +} -- cgit v1.2.3