summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/SNIP/wc.c
blob: 62bc276df54e5a50abd7edf889166850487fb748 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
   File wc.c - a sample word count program
   Written and submitted to public domain by Jay Elkes
   April, 1992
*/

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main (int argc, char *argv[])
{
      FILE *infileptr;
      char infile[80];

      long int nl = 0;
      long int nc = 0;
      long int nw = 0;

      int state = 0;
      const int  NEWLINE = '\n';
      int  c;

/*  The program name itself is the first command line arguement so we
    ignore it (argv[0]) when showing user entered parameters. */

      switch (argc - 1)
      {
      case (0):
            printf("no parameters\n");
            return 12;
      case (1):
            break;
      default:
            printf("too many parameters\n");
            return 12;
      }

      strcpy(infile,argv[1]);

      infileptr = fopen(infile,"rb");
      if (infileptr == NULL)
      {
            printf("Cannot open %s\n",infile);
            return 12;
      }

      while ((c = getc(infileptr)) != EOF)
      {
            ++nc;
            if (c == NEWLINE)
                  ++nl;
            if (isspace(c))
                  state = 0;
            else if (state == 0)
            {
                  state = 1;
                  ++nw;
            }
      }

      /* Final Housekeeping */

      printf("%ld Lines, %ld Words, %ld Characters", nl, nw, nc);
      return 0;
}