From d779c0b056defcf7eb4d75ab510e168ee03b5d95 Mon Sep 17 00:00:00 2001 From: Tom Ryder Date: Tue, 7 Jan 2020 10:21:27 +1300 Subject: More refactoring and rearranging, commenting --- crypt.c | 40 ++++++++++++++++++++++++++-------------- crypt.h | 6 ++++-- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/crypt.c b/crypt.c index 29c4794..5e13fbd 100644 --- a/crypt.c +++ b/crypt.c @@ -1,36 +1,40 @@ #include "crypt.h" -/* - * Main function - */ int main (int argc, char **argv) { - /* The hash we will produce, hopefully */ - char *hash = NULL; - - /* Option character */ + char *hash, *key, *salt; int opt; - /* Iterate through any options */ while ((opt = getopt(argc, argv, "h")) != -1) { switch (opt) { - case 'h': + case 'h': /* Help */ usage(stdout, EXIT_SUCCESS); break; - case '?': + case '?': /* Unknown option */ usage(stderr, EXIT_FAILURE); break; - default: + default: /* Shouldn't happen */ abort(); } } - /* If we don't have three arguments left now, bail */ + /* + * If we don't have three arguments left after processing the options, + * exit with usage information and error status + */ if (argc != 3) usage(stderr, EXIT_FAILURE); - /* All seems well, build the hash and print it */ - hash = crypt(argv[1], argv[2]); + key = argv[1]; + salt = argv[2]; + + /* + * Create the hash, but exit immediately with the system error string + * if it returns a null pointer (error condition) + */ + if (!(hash = crypt(key, salt))) + error(strerror(errno)); + puts(hash); exit(EXIT_SUCCESS); } @@ -42,3 +46,11 @@ void usage(FILE *stream, int status) { fputs("USAGE: crypt [-h | KEY SALT]\n", stream); exit(status); } + +/* + * Exit with error error message + */ +void error(char *message) { + fprintf(stderr, "%s\n", message); + exit(EXIT_FAILURE); +} diff --git a/crypt.h b/crypt.h index 6b2b7ca..6612e01 100644 --- a/crypt.h +++ b/crypt.h @@ -1,7 +1,9 @@ #define _XOPEN_SOURCE -#include +#include #include #include -#include +#include /* strerror(3) */ +#include /* crypt(3) */ void usage(FILE *, int); +void error(char *); -- cgit v1.2.3