aboutsummaryrefslogblamecommitdiff
path: root/main.c
blob: 620cc41c0b3ca2fd117a29702c691af250a3a649 (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 (cfd(0, 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 (cfd(0, buf) == -1) {
            exv = EXIT_FAILURE;
        }
    }

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

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