home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 11 Util / 11-Util.zip / WC2.ZIP / WC.C < prev    next >
Text File  |  1991-03-24  |  2KB  |  69 lines

  1. /*
  2.  * Name:        wc.c
  3.  * Synopsis:    wc < -lwc > < file_name ... >
  4.  * Description: This program is modeled after the UNIX "wc" program.
  5.  *              Input is from STDIN or from file_name.  The program
  6.  *              counts the lines, words, and characters in the file
  7.  *              and displays the results to the console.  The default
  8.  *              is -lwc and displays in that order, but any order can
  9.  *              be chosen.
  10.  *
  11.  *              Options are:
  12.  *                  l - line count
  13.  *                  w - word count
  14.  *                  c - character count
  15.  */
  16.  
  17. #include <stdio.h>
  18. #define  IN     1
  19. #define  OUT    0
  20.  
  21. char *defopts = "lwc";
  22. long i, c, lines, words, chars, state;
  23. char *opts, *p1;
  24. FILE *fdi;
  25. int f_ctr;
  26.  
  27. main(int argc, char *argv[], char *envp[])
  28. {
  29.     f_ctr = argc;
  30.     opts = defopts;
  31.     for (i=1;i<argc;i++) {
  32.         if (*argv[i] == '-') {
  33.             opts = argv[i];
  34.             opts++;
  35.             f_ctr--;
  36.         }
  37.         else {
  38.             if( fdi = fopen(argv[i],"r")) lwc_file(argv[i]);
  39.             else printf("Could not open %s.\n",argv[i]);
  40.         }     
  41.     }
  42.     if (f_ctr == 1) {
  43.         fdi = stdin;
  44.         lwc_file("");
  45.     }
  46. }
  47.  
  48. lwc_file(char *file_name)
  49. {
  50.     state = OUT;
  51.     lines = words = chars = 0;
  52.     while ((c = fgetc(fdi)) != EOF) {
  53.         ++chars;
  54.         if (c == '\n') ++lines;
  55.         if (c == ' ' || c == '\n' || c == '\t') state = OUT;
  56.         else if (state == OUT) {
  57.             state = IN;
  58.             ++words;
  59.         }
  60.     }
  61.     for (p1=opts;*p1;p1++) {
  62.         if (*p1 == 'l') printf("%10ld",lines);
  63.         else if(*p1 == 'w') printf("%10ld",words); 
  64.         else if(*p1 == 'c') printf("%10ld",chars);
  65.     }
  66.     printf("  %s\n", file_name);
  67.     if (fdi != stdin) fclose(fdi);
  68. }
  69.