cat.c (1505B)
- // Collection of Unix tools, comparable to coreutils
- // SPDX-FileCopyrightText: 2017-2022 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only
- #define _POSIX_C_SOURCE 200809L
- #include <errno.h> /* errno */
- #include <fcntl.h> /* open(), O_RDONLY */
- #include <stdio.h> /* fprintf(), BUFSIZ */
- #include <string.h> /* strerror(), strncmp() */
- #include <unistd.h> /* read(), write(), close() */
- int
- concat(int fd, const char *fdname)
- {
- ssize_t c;
- char buf[BUFSIZ];
- while((c = read(fd, buf, sizeof(buf))) > 0)
- {
- if(write(1, buf, (size_t)c) < 0)
- {
- fprintf(stderr, "\nError writing: %s\n", strerror(errno));
- return 1;
- }
- }
- if(c < 0)
- {
- fprintf(stderr, "\nError reading ‘%s’: %s\n", fdname, strerror(errno));
- return 1;
- }
- return 0;
- }
- int
- main(int argc, char *argv[])
- {
- if(argc <= 1)
- {
- return concat(0, "<stdin>");
- }
- for(int argi = 1; argi < argc; argi++)
- {
- if(strncmp(argv[argi], "-", 2) == 0)
- {
- if(concat(0, "<stdin>") != 0)
- {
- return 1;
- }
- }
- else if(strncmp(argv[argi], "--", 3) == 0)
- {
- continue;
- }
- else
- {
- int fd = open(argv[argi], O_RDONLY);
- if(fd < 0)
- {
- fprintf(stderr, "\nError opening ‘%s’: %s\n", argv[argi], strerror(errno));
- return 1;
- }
- if(concat(fd, argv[argi]) != 0)
- {
- return 1;
- }
- if(close(fd) < 0)
- {
- fprintf(stderr, "\nError closing ‘%s’: %s\n", argv[argi], strerror(errno));
- return 1;
- }
- }
- }
- return 0;
- }