aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

cat.c (1487B)


      1 /* see LICENSE file for copyright and license details */
      2 
      3 #include <fcntl.h>
      4 #include <string.h>
      5 #include <unistd.h>
      6 
      7 #include "util.h"
      8 
      9 static void
     10 usage(void)
     11 {
     12   eprintf("usage: %s [-u] [file ...]\n", argv0);
     13 }
     14 
     15 // ?man cat: concatenate files and print to standard output
     16 // ?man arguments: file ...
     17 // ?man cat reads each file in sequence and writes it to standard output
     18 // ?man if no file is given, or a file is -, standard input is read
     19 int
     20 main(int argc, char *argv[])
     21 {
     22   int fd, ret = 0;
     23 
     24   ARGBEGIN
     25   {
     26     case 'u':
     27       // ?man -u: ignored; accepted for posix compatibility; output is always unbuffered
     28       break;
     29     default:
     30       usage();
     31   }
     32   ARGEND
     33 
     34   if (!argc) {
     35     if (concat(0, "<stdin>", 1, "<stdout>") < 0)
     36       ret = 1;
     37   } else {
     38     for (; *argv; argc--, argv++) {
     39       if (!strcmp(*argv, "-")) {
     40         *argv = "<stdin>";
     41         fd    = 0;
     42       } else if ((fd = open(*argv, O_RDONLY)) < 0) {
     43         weprintf("open %s:", *argv);
     44         ret = 1;
     45         continue;
     46       }
     47       switch (concat(fd, *argv, 1, "<stdout>")) {
     48         case -1:
     49           ret = 1;
     50           break;
     51         case -2:
     52           return 1; /* exit on write error */
     53       }
     54       if (fd != 0)
     55         close(fd);
     56     }
     57   }
     58 
     59   // ?man
     60   // ?man ## Exit status
     61   // ?man
     62   // ?man cat exits 0 on success, and >0 if an error occurs reading any file
     63   // ?man or writing to standard output
     64   // ?man
     65   // ?man ## see also
     66   // ?man
     67   // ?man cp(1), dd(1)
     68   // ?man
     69 
     70   return ret;
     71 }