about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorphoebos <ben@bvnf.space>2021-07-06 20:26:21 +0100
committerphoebos <ben@bvnf.space>2021-07-06 20:26:21 +0100
commitbc4022292b3366ef3f4dfbdd1347aa15c8297e83 (patch)
tree347a248dfb01eefe43e5dd57bfe754af5edcb0ac
parent1e59a135d33a8f3da633852add2551f8f9b2b624 (diff)
downloadkandr-bc4022292b3366ef3f4dfbdd1347aa15c8297e83.tar.gz
base64: only work on one file/stdin
-rw-r--r--base64.c46
1 files changed, 24 insertions, 22 deletions
diff --git a/base64.c b/base64.c
index 87843d6..ce4f4c7 100644
--- a/base64.c
+++ b/base64.c
@@ -54,33 +54,35 @@ int main(int argc, char **argv) {
                 break;
         }
     }
+    /* only work on one file */
+    if (optind + 1 < argc) {
+        fprintf(stderr, "too many arguments\n");
+        usage(name);
+        return 2;
+    }
     int fd;
-    if (optind == argc) {
-        base64(STDIN_FILENO, dflg);
+    if (optind == argc || *argv[optind] == '-') {
+        fd = STDIN_FILENO;
     } else {
-        for (; optind < argc; optind++) {
-            if (*argv[optind] == '-') {
-                fd = STDIN_FILENO;
-            } else {
-                if ((fd = open(argv[optind], O_RDONLY)) == -1 ) {
-                    perror(argv[optind]);
-                    return 1;
-                }
-            }
-            char buf[BUF_SIZE] = {'\0'};
-            if (read(fd, buf, BUF_SIZE) == -1 ) {
-                perror("read");
-                return 1;
-            }
-            printf("%s\n", buf);
-
-            if (close(fd) != 0) {
-                perror("close");
-                return 1;
-            }
+        if ((fd = open(argv[optind], O_RDONLY)) == -1 ) {
+            perror(argv[optind]);
+            return 1;
         }
     }
+    char buf[BUF_SIZE] = {'\0'};
+    if (read(fd, buf, BUF_SIZE) == -1 ) {
+        perror("read");
+        return 1;
+    }
+
+    if (close(fd) != 0) {
+        perror("close");
+        return 1;
+    }
 
+    char *output = base64(buf, dflg);
+    printf("%s\n", buf);
+    printf("%s\n", output);
 
     return 0;