commit 08c8ffa8fbf6f600099e6e2dc9c5af55daf094e6
parent 53b38e0a1a143a7395e1bdf919be2f6b689c94c4
Author: Jacob R. Edwards <jacobouno@protonmail.com>
Date: Sun, 18 Apr 2021 02:51:49 -0700
Simplify error handling
Rework the die function to simply take a char * and use errno to
describe errors allowing a single error message to be used for
multiple different errors (see loadimg).
Diffstat:
M | lel.c | | | 45 | ++++++++++++++++++++++----------------------- |
1 file changed, 22 insertions(+), 23 deletions(-)
diff --git a/lel.c b/lel.c
@@ -56,25 +56,28 @@ static int winx, winy, reqwinwidth = 320, reqwinheight = 240;
static float zoominc = 0.25;
static void
-die(const char *fmt, ...)
+edie(int e, char *s)
{
- va_list ap;
-
- va_start(ap, fmt);
- vfprintf(stderr, fmt, ap);
- va_end(ap);
-
- if (fmt[0] && fmt[strlen(fmt) - 1] == ':') {
- fputc(' ', stderr);
- perror(NULL);
- }
+ fputs(getprogname(), stderr);
+ if (s)
+ fprintf(stderr, ": %s", s);
+ if (e)
+ fprintf(stderr, ": %s", strerror(e));
+ fputs(".\n", stderr);
exit(1);
}
static void
+die(char *s)
+{
+ edie(errno, s);
+}
+
+static void
usage(void)
{
- die("usage: %s [-afv] [file...]\n", getprogname());
+ fprintf(stderr, "usage: %s [-afv] [file...]\n", getprogname());
+ exit(1);
}
static int
@@ -84,6 +87,7 @@ ff_open(struct img *img, FILE *fp)
if (img->state & LOADED)
return 0;
+ errno = EFTYPE;
if (fread(hdr, sizeof(*hdr), 4, fp) != 4)
return -1;
@@ -97,9 +101,9 @@ ff_open(struct img *img, FILE *fp)
return -1;
if (!(img->buf = malloc(img->width * img->height * 4)))
- die("malloc:");
+ die("malloc");
- return 0;
+ return errno = 0;
}
static int
@@ -118,7 +122,8 @@ ff_read(struct img *img, FILE *fp)
for (off = 0, i = 0; i < img->height; ++i) {
if (fread(row, 1, (size_t)row_len, fp) != (size_t)row_len) {
free(row);
- die("unexpected EOF or row-skew at %d\n", i);
+ errno = EFTYPE;
+ return -1;
}
for (j = 0; j < row_len / 2; j += 4, off += 4) {
img->buf[off] = row[j];
@@ -165,14 +170,8 @@ loadimg(void)
FILE *fp;
fp = fopen(imgs[img.index], "rb");
- if (fp == NULL)
- die("open %s\n", imgs[img.index]);
- if (ff_open(&img, fp))
- die("can't open image (invalid format?)\n");
- if (ff_read(&img, fp))
- die("can't read image\n");
- if (fclose(fp) != 0)
- die("close %s\n", imgs[img.index]);
+ if (fp == NULL || ff_open(&img, fp) || ff_read(&img, fp) || fclose(fp))
+ die(imgs[img.index]);
reqwinwidth = img.width;
reqwinheight = img.height;