/******************************************************************************
 *  This program simulates the basic functionality of the UNIX command 'cat',
 *  using File I/O operations, standard buffers, and command-line inputs in C.
 *
 *  Compile : gcc -o dog dog.c
 *  Usage   : ./dog <filename_1> <filename_2> ... <filename_k>
 *  Output  : Concatenated print of all input files on the screen
 ******************************************************************************/

#include <stdio.h>

void filecopy (FILE *, FILE *);    /* Declaration for the primary filecopy function. */

int main (int argc, char *argv[]) {    /* Keep provision for command-line inputs */
    FILE *fp;
    char *prog = argv[0];    /* argv[0] contains the 'name' of the executable program */

    if (argc == 1) {
        /* In case there are no files as input, copy stdin to stdout. */
        filecopy (stdin, stdout);
    } else {
        /* Each file provided as input, as in *argv[], must be copied to stdout. */
        while (--argc > 0) {
            if ((fp = fopen(*++argv, "r")) == NULL) {
                /* If fopen fails for a certain input file, print error in stderr. */
		        printf("%s: %s: No such file or directory", prog, *argv);
            } else {
                /* Otherwise, copy the input file to stdout, and close the input. */
		        filecopy(fp, stdout);
		        fclose(fp);
            }
        }
    }
    return 0;
}

/* This function copies (character-wise) an input file to the specified output file. */
void filecopy (FILE *inputf, FILE *outputf) {
    int c;
    while ((c = fgetc(inputf)) != EOF)
        putc(c, outputf);
}
