/** * cat file1 file2 ... filen * Print out the contents of the given files. Based on code * from sections 7.5 and 7.6 of K&R. */ // +---------+-------------------------------------------------------- // | Headers | // +---------+ #include // +---------+-------------------------------------------------------- // | Helpers | // +---------+ /** * filecopy(ifp, ofp) * Copy from ifp to ofp. */ void filecopy (FILE *ifp, FILE *ofp) { int c; while ((c = getc (ifp)) != EOF) putc (c, ofp); } // filecopy // +------+----------------------------------------------------------- // | Main | // +------+ int main (int argc, char *argv[]) { FILE *fp; // The current input file. char *prog = argv[0]; // The name of the program, used for output // If no file names are given, copy from standard input to standard output. if (argc == 1) filecopy (stdin, stdout); // Normal behavior: Print contents of all files to stdout else { // As long as files remain while (--argc > 0) { // Grab the current file fp = fopen (*++argv, "r"); // Check for failure if (fp == NULL) { fprintf (stderr, "%s: can't open file %s\n", prog, *argv); return 1; } // Yay! The open succeeded. Print the file and close it. filecopy (fp, stdout); fclose (fp); } // while } // normal behavior // Did something go wrong? If so, indicate that an error occured. if (ferror (stdout)) { fprintf (stderr, "%s: error writing to stdout\n", prog); return 2; } // if something went wrong // Okay, nothing went wrong return 0; } // main