home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / prof_c / 06user / cat.c next >
Encoding:
C/C++ Source or Header  |  1988-08-11  |  1.6 KB  |  82 lines

  1. /*
  2.  *    cat -- concatenate files
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <local\std.h>
  8.  
  9. main(argc, argv)
  10. int argc;
  11. char **argv;
  12. {
  13.     int ch;
  14.     char *cp;
  15.     FILE *fp;
  16.     BOOLEAN errflag, silent;
  17.     static char pgm[MAXNAME + 1] = { "cat" };
  18.  
  19.     extern void getpname(char *, char *);
  20.     extern int fcopy(FILE *, FILE *);
  21.     extern int getopt(int, char **, char *);
  22.     extern int optind;
  23.     extern char *optarg;
  24.  
  25.     /* use an alias if one is given to this program */
  26.     if (_osmajor >= 3)
  27.         getpname(*argv, pgm);
  28.  
  29.     /* process optional arguments, if any */
  30.     errflag = FALSE;
  31.     silent = FALSE;
  32.     while ((ch = getopt(argc, argv, "s")) != EOF)
  33.         switch (ch) {
  34.         case 's':
  35.             /* don't complain about non-existent files */
  36.             silent = TRUE;
  37.             break;
  38.         case '?':
  39.             /* say what? */
  40.             errflag = TRUE;
  41.             break;
  42.         }
  43.     if (errflag == TRUE) {
  44.         fprintf(stderr, "Usage: %s [-s] file...\n", pgm);
  45.         exit(1);
  46.     }
  47.  
  48.     /* process any remaining arguments */
  49.     argc -= optind;
  50.     argv += optind;
  51.     if (argc == 0)
  52.         /* no file names -- use standard input */
  53.         if (fcopy(stdin, stdout) != 0) {
  54.             fprintf(stderr, "error copying stdin");
  55.             exit(2);
  56.         }
  57.         else
  58.             exit(0);
  59.  
  60.     /* copy the contents of each named file to standard output */
  61.     for (; argc-- > 0; ++argv) {
  62.         if ((fp = fopen(*argv, "r")) == NULL) {
  63.             if (silent == FALSE)
  64.                 fprintf(stderr, "%s: can't open %s\n",
  65.                     pgm, *argv);
  66.             continue;
  67.         }
  68.         if (fcopy(fp, stdout) != 0) {
  69.             fprintf(stderr, "%s: Error while copying %s",
  70.                 pgm, *argv);
  71.             exit(3);
  72.         }
  73.         if (fclose(fp) != 0) {
  74.             fprintf(stderr, "%s: Error closing %s",
  75.                 pgm, *argv);
  76.             exit(4);
  77.         }
  78.     }
  79.  
  80.     exit(0);
  81. }
  82.