logo

utils-std

Collection of commonly available Unix tools
commit: 5b886a7ee7e64856e30b69332f63773703cdf768
parent 3d699fc33f744ab5ef71b3f1b0730338aeee5064
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date:   Mon,  1 Apr 2024 10:50:41 +0200

cmd/cat.c: Use getopt instead of hacks

Diffstat:

Mcmd/cat.c54+++++++++++++++++++++++++++++++++++++-----------------
Mtest-cmd/cat2+-
2 files changed, 38 insertions(+), 18 deletions(-)

diff --git a/cmd/cat.c b/cmd/cat.c @@ -3,14 +3,15 @@ // SPDX-License-Identifier: MPL-2.0 #define _POSIX_C_SOURCE 200809L -#define _GNU_SOURCE /* splice(2) */ +#define _GNU_SOURCE // splice #include <assert.h> #include <errno.h> -#include <fcntl.h> /* open(), O_RDONLY, splice(2) */ -#include <stdint.h> /* SIZE_MAX */ -#include <stdio.h> /* fprintf(), BUFSIZ */ -#include <string.h> /* strerror(), strncmp() */ -#include <unistd.h> /* read(), write(), close() */ +#include <fcntl.h> // open, O_RDONLY, splice +#include <stdint.h> // SIZE_MAX +#include <stdio.h> // fprintf, BUFSIZ +#include <stdlib.h> // abort +#include <string.h> // strerror, strncmp +#include <unistd.h> // read, write, close, getopt static int concat(int fd, const char *fdname) @@ -75,22 +76,45 @@ again: #define fd_copy concat #endif // HAS_SPLICE +static void +usage() +{ + fprintf(stderr, "Usage: cat [-u] [files ...]\n"); +} + int main(int argc, char *argv[]) { - if(argc <= 1) + int c = -1; + while((c = getopt(argc, argv, ":u")) != -1) { - return fd_copy(0, "<stdin>"); + switch(c) + { + case 'u': + // POSIX: Ignored, buffered streams aren't used + break; + case ':': + fprintf(stderr, "cat: Error: Missing operand for option: '-%c'\n", optopt); + usage(); + return 1; + case '?': + fprintf(stderr, "cat: Error: Unrecognised option: '-%c'\n", optopt); + usage(); + return 1; + default: + abort(); + } } - // For POSIX compatibility - if(strncmp(argv[1], "-u", 3) == 0) + argc -= optind; + argv += optind; + + if(argc < 1) { - argc--; - argv++; + return fd_copy(0, "<stdin>"); } - for(int argi = 1; argi < argc; argi++) + for(int argi = 0; argi < argc; argi++) { if(strncmp(argv[argi], "-", 2) == 0) { @@ -99,10 +123,6 @@ main(int argc, char *argv[]) return 1; } } - else if(strncmp(argv[argi], "--", 3) == 0) - { - continue; - } else { assert(errno == 0); diff --git a/test-cmd/cat b/test-cmd/cat @@ -61,7 +61,7 @@ atf_test_case doubledash doubledash_body() { atf_check -o file:inputs/all_bytes -- ../cmd/cat -- inputs/all_bytes # shellcheck disable=SC1112 - atf_check -s exit:1 -e 'inline:cat: Error opening ‘---’: No such file or directory\n' -o empty -- ../cmd/cat --- inputs/all_bytes + atf_check -s exit:1 -e "inline:cat: Error: Unrecognised option: '--'\nUsage: cat [-u] [files ...]\n" -o empty -- ../cmd/cat --- inputs/all_bytes } atf_init_test_cases() {