|
|
1.1 root 1: /*
2: * wc - word count
3: * Counts characters, lines, and words in all
4: * of the input files.
5: *
6: * Usage: wc [-lwc] [name ...]
7: */
8:
9: #include <stdio.h>
10: #ifdef COHERENT
11: #include <access.h>
12: #endif
13:
14: char _cmdname[] = "wc";
15: int nfiles;
16: int lineflg;
17: int wordflg;
18: int charflg;
19: long chars, words, lines;
20: long tchars, twords, tlines;
21:
22: main(argc, argv)
23: char *argv[];
24: {
25: register int i = 0;
26: register char *ap;
27: register FILE *fp;
28:
29: while (argv[1] != NULL && *argv[1] == '-') {
30: for (ap = &argv[1][1]; *ap; ap++)
31: switch (*ap) {
32: case 'l':
33: lineflg = 1;
34: break;
35:
36: case 'w':
37: wordflg = 1;
38: break;
39:
40: case 'c':
41: charflg = 1;
42: break;
43:
44: default:
45: usage();
46: }
47: argv++;
48: argc--;
49: }
50: if (argc == 1) {
51: #ifdef MSDOS
52: _setbinary(stdin);
53: #endif
54: wc(stdin);
55: print(NULL);
56: } else {
57: argv++; /* adjust args */
58:
59: while (*argv)
60: {
61: #ifdef COHERENT
62: if (access(*argv, AREAD))
63: { fprintf(stderr, "wc: can't open %s\n", *argv);
64: *argv[0] = 0; /* flag arg as invalid */
65: }
66: #endif
67: i++; /* count the arg */
68: argv++; /* advance to next arg */
69: }
70:
71: argv -= i; /* back to start of filename args to process */
72: argc--;
73:
74: for (i=0; i<argc; i++) {
75: if (*argv[i] == 0) /* arg to skip? */
76: continue; /* yes */
77: if ((fp = fopen(argv[i], "rb")) == NULL) {
78: fprintf(stderr,
79: "wc: can't open %s\n", argv[i]);
80: continue;
81: }
82: nfiles++;
83: wc(fp);
84: print(argv[i]);
85: tchars += chars;
86: twords += words;
87: tlines += lines;
88: fclose(fp);
89: }
90: if (nfiles >= 2) {
91: chars = tchars;
92: words = twords;
93: lines = tlines;
94: print("Total");
95: }
96: }
97: }
98:
99: /*
100: * Count words, lines and characters in the input file
101: * descriptor and put into global variables.
102: */
103: wc(in)
104: register FILE *in;
105: {
106: register c;
107: int inw;
108:
109: inw = 0;
110: chars = words = lines = 0;
111: while ((c = getc(in)) != EOF) {
112: chars++;
113: if (c == '\n') {
114: lines++;
115: inw = 0;
116: } else if (c==' ' || c=='\t')
117: inw = 0;
118: else if (!inw) {
119: inw = 1;
120: words++;
121: }
122: }
123: }
124:
125: /*
126: * Print according to option flags to totals
127: */
128: print(name)
129: char *name;
130: {
131: if (lineflg)
132: printf("%8ld", lines);
133: if (wordflg)
134: printf("%8ld", words);
135: if (charflg)
136: printf("%8ld", chars);
137: if (!lineflg && !wordflg && !charflg)
138: printf("%8ld %8ld %8ld", lines, words, chars);
139: if (name != NULL)
140: printf(" %s", name);
141: printf("\n");
142: }
143:
144: usage()
145: {
146: fprintf(stderr, "Usage: wc [-lwc] [name ...]\n");
147: exit(1);
148: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.