aboutsummaryrefslogtreecommitdiff
path: root/main.c
blob: 620cc41c0b3ca2fd117a29702c691af250a3a649 (plain) (blame)
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
#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);
}