commit fda2cdb74759d14a9c9c0644fb6e5bd2505e2639
parent 8fde78de2cf95793fe4aed00b899aca2695164b6
Author: Louis Burda <quent.burda@gmail.com>
Date: Wed, 15 Feb 2023 19:11:53 +0100
Error handling with err() and simplified program
Diffstat:
M | Makefile | | | 1 | + |
M | findhex.c | | | 61 | +++++++++++++++++++++++++++++-------------------------------- |
2 files changed, 30 insertions(+), 32 deletions(-)
diff --git a/Makefile b/Makefile
@@ -1,3 +1,4 @@
+CFLAGS = -Wunused-variable -Wunused-function
all: findhex
diff --git a/findhex.c b/findhex.c
@@ -1,22 +1,8 @@
-#include <stdlib.h>
-#include <stdio.h>
+#include <err.h>
#include <string.h>
#include <stdint.h>
-#include <stdarg.h>
-
-#define MAX(a, b) ((a) > (b) ? (a) : (b))
-
-void
-die(const char *msg, ...)
-{
- va_list ap;
-
- va_start(ap, msg);
- vfprintf(stderr, "%s\n", ap);
- va_end(ap);
-
- exit(1);
-}
+#include <stdio.h>
+#include <stdlib.h>
int
main(int argc, const char **argv)
@@ -33,32 +19,44 @@ main(int argc, const char **argv)
setvbuf(stdout, NULL, _IONBF, 0);
- if (argc < 2 || argc > 3) die("Usage: findhex PATTERN [FILE]");
+ if (argc < 2 || argc > 3) {
+ printf("Usage: findhex PATTERN [FILE]\n");
+ return 0;
+ }
arglen = strlen(argv[1]);
- if (!arglen || arglen % 2 != 0)
- die("Pattern length invalid");
+ if (!arglen || arglen % 2 != 0) {
+ fprintf(stderr, "Pattern length invalid\n");
+ return 1;
+ }
patlen = arglen / 2;
- pattern = calloc(patlen, 1);
- pattern_mask = calloc(patlen, 1);
- if (!pattern || !pattern_mask) die("Out of Memory");
+ pattern = malloc(patlen);
+ if (!pattern) err(1, "malloc");
+
+ pattern_mask = malloc(patlen);
+ if (!pattern_mask) err(1, "malloc");
+
+ buflen = 16 * 1024;
+ if (patlen * 2 > buflen)
+ buflen = patlen * 2;
- buflen = MAX(patlen * 2, 16 * 1024);
buf = malloc(buflen);
- if (!buf) die("Out of Memory");
+ if (!buf) err(1, "malloc");
for (i = 0; i < arglen; i += 2) {
if (!strncmp(argv[1] + i, "__", 2))
continue;
- if (!sscanf(argv[1] + i, "%02hX", &pattern[i / 2]))
- die("Invalid hex in pattern");
+ if (!sscanf(argv[1] + i, "%02hhx", &pattern[i / 2])) {
+ fprintf(stderr, "Invalid hex in pattern\n");
+ return 1;
+ }
pattern_mask[i / 2] = 0xff;
}
if (argc == 3) {
- file = fopen(argv[1], "r");
- if (!file) die("Failed to open file");
+ file = fopen(argv[2], "r");
+ if (!file) err(1, "fopen");
} else {
file = stdin;
}
@@ -70,8 +68,7 @@ main(int argc, const char **argv)
pos = 0;
while (1) {
nread = fread(buf + off, 1, buflen - off, file);
- if (nread == 0) break;
- if (nread < 0) die("%016llX: Read failed", pos);
+ if (nread <= 0) break;
for (i = 0; i <= nread + off - patlen; i++) {
for (k = 0; k < patlen; k++) {
@@ -81,7 +78,7 @@ main(int argc, const char **argv)
break;
}
if (k == patlen)
- printf("%016llX\n", pos + i);
+ printf("%016lX\n", pos + i);
}
pos += nread;