Log in Register Dashboard Temp Share Shortlinks Frames API

HTMLify

head
Views: 31 | Author: abh
/* head */

#define _POSIX_C_SOURCE 202405L

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>

struct args {
    int bytes;
    int lines;
} args = { -1, 10 };

void head_file(FILE *file) {
    int byte, bytes = args.bytes, lines = args.lines;
    while (((byte = fgetc(file)) != EOF) && lines && bytes) {
        fprintf(stdout, "%c", byte);
        if (byte == 10 && lines > 0)
            lines--;
        if (bytes > 0)
            bytes--;
    }
}

int main(int argc, char *argv[]) {
    int opt, i, exit_code = 0;

    while ((opt = getopt(argc, argv, "c:n:")) != -1) {
        switch (opt) {
            case 'c': {
                for (i=0; i<strlen(optarg); i++) {
                    if (!isdigit(optarg[i])) {
                        fprintf(stderr, "head: invalid number of bytes: '%s'\n", optarg);
                        return 1;
                    }
                }
                args.bytes = atoi(optarg);
                args.lines = -1;
                break;
            }
            case 'n': {
                for (i=0; i<strlen(optarg); i++) {
                    if (!isdigit(optarg[i])) {
                        fprintf(stderr, "head: invalid number of lines: '%s'\n", optarg);
                        return 1;
                    }
                }
                args.lines = atoi(optarg);
                args.bytes = -1;
                break;
            }
            dfeault : {
                exit_code = 1;
            }
        }
    }
    argc -= optind;
    argv += optind;

    FILE *file;
    if (argc == 0) {
        head_file(stdin);
        return exit_code;
    } else {
        for (i=0; i<argc; i++) {
            if (!strcmp(argv[i], "-")) {
                file = stdin;
            } else {
                file = fopen(argv[i], "r");
            }
            if (file == NULL) {
                fprintf(stderr, "head: %s: Unable to open file\n", argv[i]);
                exit_code = 1;
                continue;
            }
            if (argc > 1) {
                if (i) printf("\n");
                if (!strcmp(argv[i], "-")) {
                    printf("==> standard input <==\n");
                } else {
                    printf("==> %s <==\n", argv[i]);
                }
            }
            head_file(file);
            rewind(file);
        }
    }

    return exit_code;
}

Comments