home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / vol_100 / 154_01 / wc.c < prev    next >
Text File  |  1979-12-31  |  2KB  |  100 lines

  1. /* wc.c:    word count */
  2.  
  3. /* From Kernighan/Ritchie C, by Chuck Allison */
  4.  
  5. #include <stdio.h>
  6. #include <ctype.h>
  7.  
  8. #define yes 1
  9. #define no 0
  10. #define MAXFILES 150
  11.  
  12. int bytes = no, words = no, lines = no, files = no;
  13.  
  14. main(argc,argv)
  15. int argc;
  16. char *argv[];
  17. {
  18.     FILE *f;
  19.     char *s, *xargv[MAXFILES];
  20.     int dash = no, maxarg = MAXFILES, xargc, i;
  21.  
  22.     /* ..process switches.. */
  23.     for ( ; *(s = *(argv+1)) == '-'; ++argv, --argc)
  24.     {
  25.         dash = yes;
  26.         while (*++s)
  27.             switch(tolower(*s)) {
  28.                 case 'l':
  29.                     lines = !lines;
  30.                     break;
  31.                 case 'w':
  32.                     words = !words;
  33.                     break;
  34.                   case 'c':
  35.                     bytes = !bytes;
  36.                     break;
  37.                 case 'f':
  38.                     files = !files;
  39.                     break;
  40.                 default :
  41.                     fprintf(stderr,"unknown switch: -%c\n",*s);
  42.                     exit(1);
  43.             }
  44.     }
  45.  
  46.     if (dash == no) bytes = words = lines = yes;
  47.  
  48.     /* ..process files.. */
  49.     if (argc == 1)
  50.         wc(stdin,"");
  51.     else
  52.     {
  53.         /* ..expand filespecs (Mark Williams C only!).. */
  54.         xargc = exargs("",argc,argv,xargv,maxarg);
  55.  
  56.         /* ..check file switch.. */
  57.         if (xargc > 1) files = !files;
  58.  
  59.         for (i = 0; i < xargc; ++i)
  60.             if ((f = fopen(xargv[i],"r")) != NULL)
  61.             {
  62.                 wc(f,xargv[i]);
  63.                 fclose(f);
  64.             }
  65.             else
  66.                 fprintf(stderr,"can't open: %s\n",xargv[i]);
  67.     }
  68. }
  69.  
  70. wc(fp,s)
  71. FILE *fp;
  72. char *s;
  73. {
  74.     long c, kc, kl, kw;
  75.     int inword;
  76.  
  77.     kc = kw = kl = 0L;
  78.     inword = no;
  79.  
  80.     while ((c = fgetc(fp)) != EOF)
  81.     {
  82.         kc++;
  83.         if (c == '\n')
  84.             kl++;
  85.         if (isspace(c))
  86.             inword = no;
  87.         else if (!inword)
  88.         {
  89.             inword = yes;
  90.             kw++;
  91.         }
  92.     }
  93.     fclose(fp);
  94.     if (files) printf("%-20s :   ",s);
  95.     if (bytes) printf("%8D ",kc);
  96.     if (words) printf("%7D ",kw);
  97.     if (lines) printf("%6D ",kl);
  98.     putchar('\n');
  99. }
  100.