From f041ae5d63f878576818ece99685d7d8cce380e3 Mon Sep 17 00:00:00 2001 From: emma Date: Mon, 14 Aug 2023 11:45:43 -0600 Subject: [PATCH] cat(1p): cleanup --- src/cat.c | 46 +++++++++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 17 deletions(-) diff --git a/src/cat.c b/src/cat.c index 3fc2a72..7047c1f 100644 --- a/src/cat.c +++ b/src/cat.c @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -29,26 +30,26 @@ void cat(FILE *file, bool u) { int p = 0; /* index counter for bytes in buffered reading */ char buf[4096]; /* buffer for buffered reading */ - while (byte != EOF) { - byte = fgetc(file); - - if (u) { + if (u) { + while (byte != EOF) { + byte = fgetc(file); putchar(byte); - } else { + } + } else { + while (byte != EOF) { + byte = fgetc(file); if (p > sizeof(buf)) { fputs(buf, stdout); p = 0; + } else { + buf[p] = byte; + p += 1; } - - buf[p] = byte; - p += 1; } + + fwrite(buf, 1, p, stdout); + fflush(stdout); } - - fwrite(buf, 1, p, stdout); - fflush(stdout); - - if (file != stdin) { fclose(file); } } int main(int argc, char *argv[]) { @@ -91,11 +92,20 @@ int main(int argc, char *argv[]) { } FILE *file; + struct stat stats; + for (i = optind; i < argc; i++) { - if (argv[i][0] == '-' && argv[i][1] != '\0') { - continue; - } else if (argv[i][0] == '-' && argv[i][1] == '\0') { - file = stdin; + if (argv[i][0] == '-') { + switch (argv[i][1]) { + case '\0': + file = stdin; + break; + default: + continue; + } + } else if (stat(argv[i], &stats) == 0 && S_ISDIR(stats.st_mode)) { + fprintf(stderr, "%s: %s: Is a directory.\n", argv[0], argv[i]); + return EX_NOINPUT; } else if ((file = fopen(argv[i], "r")) == NULL) { switch (errno) { case EACCES: @@ -118,7 +128,9 @@ int main(int argc, char *argv[]) { return EX_UNAVAILABLE; } } + cat(file, u); + if (file != stdin) { fclose(file); } } return EX_OK;