diff options
author | Erik K <erikk@previousplan.org> | 2022-05-13 17:24:26 +0000 |
---|---|---|
committer | Erik K <erikk@previousplan.org> | 2022-05-13 17:24:26 +0000 |
commit | b2fada1dd19211d71e04557653d08e697134a6ce (patch) | |
tree | 063b6d1280193046321db1e53506be5b72d2220f /util.c |
initial commit
Diffstat (limited to 'util.c')
-rw-r--r-- | util.c | 83 |
1 files changed, 83 insertions, 0 deletions
@@ -0,0 +1,83 @@ +#include <errno.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#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); +} |