bore

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

head.c (1931B)


      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
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
#define _XOPEN_SOURCE 700
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int
head(FILE *f, int n) {
    int i;
    ssize_t bytes;
    char *buf = NULL;
    size_t len = 0;
    for (i = 0; i < n; i++) {
        bytes = getline(&buf, &len, f);
        if (bytes == -1) {
            if (ferror(f)) {
                fprintf(stderr, "head: %s\n", strerror(errno));
                return 1;
            }
            if (feof(f))
                break;
        }
        if (write(1, buf, bytes) == -1) {
            fprintf(stderr, "head: %s\n", strerror(errno));
            return 1;
        }
    }
    free(buf);

    return 0;
}

int
main(int argc, char **argv) {
    int n = 10;
    int ret = 0;

    int c;
    while ((c = getopt(argc, argv, ":n:")) != -1) {
        switch (c) {
            case 'n':
                n = atoi(optarg);
                if (n <= 0) {
                    fprintf(stderr, "head: invalid number '%s'\n", optarg);
                    return 1;
                }
                break;
            case ':':
            case '?':
                fprintf(stderr, "usage: %s [-n num] [file...]\n", *argv);
                return 1;
        }
    }

    argc -= optind;
    argv += optind - 1;


    if (argc == 0)
        return head(stdin, n);

    FILE *f;
    while (*++argv) {
        if (**argv == '-' && *(*argv + 1) == '\0')
            f = stdin;
        else {
            f = fopen(*argv, "r");
            if (f == NULL) {
                fprintf(stderr, "head: %s: %s\n", *argv, strerror(errno));
                ret = 1;
                continue;
            }
        }
        if (head(f, n) != 0)
            ret = 1;

        if (f != stdin && fclose(f) == EOF) {
            fprintf(stderr, "head: %s: %s\n", *argv, strerror(errno));
            ret = 1;
            continue;
        }
    }
    return ret;
}