etc

small bits of code not worth their own repo
git clone git://git.benoneill.xyz/etc
Log | Files | Refs | README | LICENSE

commit 53940c2db699cb18a489dac4707b2c9ced866fba
parent b1ffabc05ff5a0bdef9275bbed7bf7b72302c696
Author: Ben O'Neill <ben@benoneill.xyz>
Date:   Tue, 20 Jul 2021 10:30:46 -0400

fortune: cleanup

Diffstat:
Mfortune.c | 39+++++++++++++++++++++++----------------
1 file changed, 23 insertions(+), 16 deletions(-)

diff --git a/fortune.c b/fortune.c @@ -1,35 +1,46 @@ -/* simple fortune(1) implementation. License: MIT */ +/* simple fortune(1) implementation with added option to choose a + * field separator. + * Author: Ben O'Neill <ben@benoneill.xyz> + * License: MIT + */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> -int fortune(FILE *ffile, char sep); +void fortune(FILE *ffile, char sep); char sep = '\n'; // default separator int main(int argc, char *argv[]) { - FILE *ffile; + FILE *fp; if (argc == 1) { - fprintf(stderr, "a fortune file must be provided.\n"); - return 1; + fp = fopen("/lib/fortunes"); return 1; } if (argc > 3) { fprintf(stderr, "too many arguments.\n"); - return 1; + return EXIT_FAILURE; } - if (argc > 1) - ffile = fopen(argv[1], "r"); + if (argc > 1) { + fp = fopen(argv[1], "r"); + if (fp == NULL) { + fprintf(stderr, "can't open file\n"); + return EXIT_FAILURE + } + } if (argc > 2) sep = *argv[2]; - return fortune(ffile, sep); + fortune(fp, sep); + fclose(fp); + return EXIT_SUCCESS; } -int fortune(FILE *ffile, char sep) +/* actual fortune function */ +void fortune(FILE *ffile, char sep) { /* 255 characters per line */ int fnum = 0, buflen = 255, cur = 0, resfortune; @@ -58,17 +69,13 @@ int fortune(FILE *ffile, char sep) if (cur == resfortune) { if (sep == '\n') { printf("%s", linebuf); - goto cleanup; + return; } while (fgets(linebuf, buflen, ffile)) { if (linebuf[0] == sep && strlen(linebuf) == 2) - goto cleanup; + return; printf("%s", linebuf); } } } - -cleanup: - fclose(ffile); - return 0; }