/* * Program to mimic "cat" command: * * With no command-line arguments, echoes text from stdin to stdout. * * With one or more command-line arguments representing filenames, * copies files to stdout. */ #include void copy_file(FILE * infile, FILE * outfile); int main(int argc, char *argv[]) { if (argc == 1) { copy_file(stdin, stdout); return 0; } else { int rval = 0; for (int i = 1; i < argc; ++i) { FILE * instream = fopen(argv[i], "r"); if (instream == NULL) { fprintf(stderr, "cannot open file %s\n", argv[i]); rval = 1; } else { copy_file(instream, stdout); fclose(instream); } } return rval; } } void copy_file(FILE * infile, FILE * outfile) { int ch; int count = 0; while ((ch = fgetc(infile)) != EOF) { fputc(ch, outfile); count += 1; } }