bore

basic core utilities (PD)
git clone git://bvnf.space/bore.git
Log | Files | Refs | README

cat.c (1393B)


      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
#define _XOPEN_SOURCE 700
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int
cat(FILE *fp, const char *fname) {
    int c = -1;

    while ((c = fgetc(fp)) != EOF) {
        putchar(c);
    }

    /* Check whether the EOF came from an end-of-file or an error. */
    if ((ferror(fp))) {
        fprintf(stderr, "cat: fgetc %s: %s\n", fname, strerror(errno));
        return 1;
    }

    return 0;
}

int
main(int argc, char **argv) {
    if (argc > 1 && **(argv + 1) == '-' && *(*(argv + 1) + 1) == 'u') {
        /* ignore -u */
        argv++;
        argc--;
    }

    if (argc == 1) {
        return cat(stdin, "stdin");
    }

    int err = 0;
    const char *fname = NULL;
    FILE *fp = NULL;

    while (*++argv) {
        if (**argv == '-' && *(*argv + 1) == '\0') {
            fp = stdin;
            fname = "stdin";
        } else {
            fp = fopen(*argv, "r");
            if (!fp) {
                fprintf(stderr, "cat: fopen %s: %s\n", *argv, strerror(errno));
                err = 1;
                continue;
            }
            fname = *argv;
        }

        if ((cat(fp, fname)) == 1) {
            err = 1;
        }

        if (fp != stdin && (fclose(fp)) == EOF) {
            fprintf(stderr, "cat: fclose %s: %s\n", fname, strerror(errno));
            err = 1;
        }
    }

    return err;
}