aboutsummaryrefslogblamecommitdiff
path: root/main.c
blob: 51ee707b09dc4a31cfc1afe89e83a79a1b38b91e (plain) (tree)


























                                                                              
                                            













                                                                           
                                    











                                   
#include "cat.h"

/* Main function */
int main(int argc, const char *argv[]) {
    int exv, i;
    void *buf;

    /* Exit value begins by assuming success */
    exv = EXIT_SUCCESS;

    /* Allocate a buffer with the prescribed size, or bail out */
    if ((buf = malloc(BUFLEN)) == NULL) {
        perror(__FUNCTION__);
        exit(EXIT_FAILURE);
    }

    /* If there's at least one argument, we'll attempt to read from all the
     * files named; if one of them doesn't work, we'll flag an error but will
     * proceed */
    if (argc > 1) {

        /* Note we start at i = 1, not i = 0; the first element of argv is the
         * command itself, not like in Perl */
        for (i = 1 ; i < argc ; i++) {

            /* If the filename is the special case of -, we emit stdin */
            if (strncmp(argv[i], "-", 1) == 0) {
                if (cfp(stdin, buf) == -1) {
                    exv = EXIT_FAILURE;
                }

            /* Otherwise, we emit the file by name */
            } else {
                if (cfn(argv[i], buf) == -1) {
                    exv = EXIT_FAILURE;
                }
            }
        }

    /* If there were no arguments, we assume the user wants us to read from
     * stdin, which should already be opened */
    } else {
        if (cfp(stdin, buf) == -1) {
            exv = EXIT_FAILURE;
        }
    }

    /* Free the allocated buffer */
    free(buf);
    buf = NULL;

    /* Done, exit appropriately */
    exit(exv);
}