/* cat.c */ #include #include #include #include /* Globals */ char * PROGRAM_NAME = NULL; /* Functions */ void usage(int status) { fprintf(stderr, "Usage: %s FILES...\n", PROGRAM_NAME); exit(status); } void cat_stream(FILE *stream) { char buffer[BUFSIZ]; while (fgets(buffer, BUFSIZ, stream)) { fputs(buffer, stdout); } } void cat_file(const char *path) { FILE *fs = fopen(path, "r"); if (fs == NULL) { fprintf(stderr, "%s: %s: %s\n", PROGRAM_NAME, path, strerror(errno)); return; } cat_stream(fs); fclose(fs); } /* Main Execution */ int main(int argc, char *argv[]) { int argind = 1; /* Parse command line arguments */ PROGRAM_NAME = argv[0]; while (argind < argc && strlen(argv[argind]) > 1 && argv[argind][0] == '-') { char *arg = argv[argind++]; switch (arg[1]) { case 'h': usage(0); break; default: usage(1); break; } } /* Process each file */ if (argind == argc) { cat_stream(stdin); } else { while (argind < argc) { char *path = argv[argind++]; if (strcmp(path, "-") == 0) { cat_stream(stdin); } else { cat_file(path); } } } return EXIT_SUCCESS; } /* vim: set sts=4 sw=4 ts=8 expandtab ft=c: */