From 106effb923bcada5d3f300e9c6820c24095be039 Mon Sep 17 00:00:00 2001 From: DTB Date: Sat, 23 Dec 2023 08:17:11 -0700 Subject: [PATCH] simplify a bit --- roll/roll.c | 74 ++++++++++++++++++++++++++--------------------------- 1 file changed, 36 insertions(+), 38 deletions(-) diff --git a/roll/roll.c b/roll/roll.c index 755f952..bc9194b 100644 --- a/roll/roll.c +++ b/roll/roll.c @@ -1,26 +1,19 @@ -#include -#include -#include +#include /* isdigit(3) */ +#include /* errno */ +#include /* fprintf(3), stderr, NULL */ +#include /* srand(3), strtol(3) */ +#include /* time(3) */ -#ifndef DONT_USE_SYSTEM_SYSEXITS +#if !defined EX_SOFTWARE || !defined EX_USAGE # include -#else -# include "../include/sysexits.h" -#endif /* ifndef DONT_USE_SYSTEM_SYSEXITS */ - -#include +#endif static char *program_name = "roll"; -/* change these to watch the world burn */ -#define ROLLS_BASE 10 -#define SIDES_BASE 10 - int main(int argc, char *argv[]){ char *argv0; char *argvc; char *ep; - extern int errno; int r; /* rolls */ int s; /* sides */ @@ -29,7 +22,8 @@ int main(int argc, char *argv[]){ if(argc < 2){ fprintf(stderr, "Usage: %s [dice...]\n" - "\tDice should be formatted [rolls]d[sides], e.g. 1d3, 5d6...\n", + "\tDice should be formatted [rolls]d[sides]," + " e.g. 1d3, 5d6...\n", argv0 == NULL ? program_name : argv0 ); return EX_USAGE; @@ -41,31 +35,21 @@ int main(int argc, char *argv[]){ argvc = *++argv; /* Parse out [rolls]d[sides] */ - if(!isdigit(**argv)){ -error: fprintf(stderr, - "%s: %s: Improperly formatted die (should be" - " [rolls]d[sides]).\n", - argv0, argvc - ); - return EX_USAGE; - } - - errno = 0; - r = strtol(*argv, &ep, ROLLS_BASE); - - if(errno != 0){ -range: fprintf(stderr, - "%s: %s: Number out of working range for this" - " program.\n", - argv0, argvc - ); - return EX_SOFTWARE; - } - - if(*(*argv = ep) != 'd' || !isdigit(*(++*argv))) + if(**argv >= 0x80 || !isdigit(**argv)) goto error; - s = strtol(*argv, &ep, SIDES_BASE); + errno = 0; + r = strtol(*argv, &ep, 10); + + if(errno != 0) + goto range; + + if(*(*argv = ep) != 'd' + || **argv >= 0x80 + || !isdigit(*(++*argv))) + goto error; + + s = strtol(*argv, &ep, 10); if(errno != 0) goto range; if(*ep != '\0') @@ -76,4 +60,18 @@ range: fprintf(stderr, } return EX_OK; + +error: fprintf(stderr, + "%s: %s: Improperly formatted die" + " (should be [rolls]d[sides]).\n", + argv0, argvc + ); + return EX_USAGE; + +range: fprintf(stderr, + "%s: %s: Number out of working range for this program.\n", + argv0, argvc + + ); + return EX_SOFTWARE; }