home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / prof_c / 08file / tee.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-08-11  |  1.4 KB  |  70 lines

  1. /*
  2.  *    tee -- a "pipe fitter" for DOS
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <local\std.h>
  9.  
  10. main(argc, argv)
  11. int argc;
  12. char *argv[];
  13. {
  14.     register int ch, n;
  15.     static char openmode[] = { "w" };
  16.     static char pgm[MAXPATH + 1] = { "tee" };
  17.     FILE *fp[_NFILE];    /* array of file pointers */
  18.  
  19.     extern int getopt(int, char **, char *);
  20.     extern int optind, opterr;
  21.     extern char *optarg;
  22.     extern void getpname(char *, char *);
  23.  
  24.     /* check for an alias */
  25.     if (_osmajor >= 3)
  26.         getpname(argv[0], pgm);
  27.  
  28.     /* process command-line options, if any */
  29.     while ((ch = getopt(argc, argv, "a")) != EOF)
  30.         switch (ch) {
  31.         case 'a':
  32.             strcpy(openmode, "a");
  33.             break;
  34.         case '?':
  35.             break;
  36.         }
  37.     n = argc -= optind;
  38.     argv += optind;
  39.  
  40.     /* check for errors */
  41.     if (argc > _NFILE) {
  42.         fprintf(stderr, "Too many files (max = %d)\n", _NFILE);
  43.         exit(1);
  44.     }
  45.  
  46.     /* open the output file(s) */
  47.     for (n = 0; n < argc; ++n) {
  48.         if ((fp[n] = fopen(argv[n], openmode)) == NULL) {
  49.             fprintf(stderr, "Cannot open %s\n", argv[n]);
  50.             continue;
  51.         }
  52.     }
  53.  
  54.     /* copy input to stdout plus opened file(s) */
  55.     while ((ch = getchar()) != EOF) {
  56.         putchar(ch);
  57.         for (n = 0; n < argc; ++n)
  58.             if (fp[n] != NULL)
  59.                 fputc(ch, fp[n]);
  60.     }
  61.  
  62.     /* close file(s) */
  63.     if (fcloseall() == -1) {
  64.         fprintf(stderr, "Error closing a file\n");
  65.         exit(2);
  66.     }
  67.  
  68.     exit(0);
  69. }
  70.