Download code

Jump to: navigation, search

Back to Word_count_(C)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

wc.c

  1 /* The authors of this work have released all rights to it and placed it
  2 in the public domain under the Creative Commons CC0 1.0 waiver
  3 (http://creativecommons.org/publicdomain/zero/1.0/).
  4 
  5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 12 
 13 Retrieved from: http://en.literateprograms.org/Word_count_(C)?oldid=15634
 14 */
 15 
 16 #include<stdio.h>
 17 #include<ctype.h>
 18 
 19 enum {OPT_C=4, OPT_W=2, OPT_L=1};
 20 
 21 int print(const char *fname, int opt, int chars, int words, int lines)
 22 {
 23 	if(opt&OPT_L) printf("% 8d", lines);
 24 	if(opt&OPT_W) printf("% 8d", words);
 25 	if(opt&OPT_C) printf("% 8d", chars);
 26 
 27 	if(fname[0]!='-') printf(" %s", fname);
 28 
 29 	putchar('\n');
 30 
 31 	return 0;
 32 }
 33 
 34 int wc(const char *fname, int opt, int *tot_chars, int *tot_words, int *tot_lines)
 35 {
 36 	int ch;
 37 	int chars=0;
 38 	int words=0;
 39 	int lines=0;
 40 	int sp=1;
 41 	FILE *fp;
 42 
 43 	if(fname[0]!='-') fp=fopen(fname, "r");
 44 	else fp=stdin;
 45 	if(!fp) return -1;
 46 
 47 	while((ch=getc(fp))!=EOF) {
 48 		++chars;
 49 		if(isspace(ch)) sp=1;
 50 		else if(sp) {
 51 			++words;
 52 			sp=0;
 53 		}
 54 		if(ch=='\n') ++lines;
 55 	}
 56 
 57 	print(fname, opt, chars, words, lines);
 58 
 59 	if(fname[0]!='-') fclose(fp);
 60 
 61 	*tot_chars+=chars;
 62 	*tot_words+=words;
 63 	*tot_lines+=lines;
 64 
 65 	return 0;
 66 }
 67 
 68 int main(int argc, char *argv[])
 69 {
 70 	int chars=0;
 71 	int words=0;
 72 	int lines=0;
 73 	int nfiles=0;
 74 	int opt=0;
 75 	int n;
 76 	while((++argv)[0] && argv[0][0]=='-') {
 77 		n=1;
 78 		while(argv[0][n]) {
 79 			switch(argv[0][n++]) {
 80 			case 'c': opt|=OPT_C; break;
 81 			case 'w': opt|=OPT_W; break;
 82 			case 'l': opt|=OPT_L; break;
 83 			default:
 84 				fprintf(stderr, "Unknown option %c\n", argv[0][n-1]);
 85 				fprintf(stderr, "Usage: wc [-cwl] [<filename>*]\n");
 86 				return -1;
 87 			}
 88 		}
 89 	}
 90 	if(!opt) opt=OPT_L|OPT_W|OPT_C;
 91 	while(argv[0]) {
 92 		++nfiles;
 93 		if(wc(*argv, opt, &chars, &words, &lines)==-1) {
 94 			perror(*argv);
 95 			return 1;
 96 		}
 97 		++argv;
 98 	}
 99 
100 	if(nfiles==0) wc("-", opt, &chars, &words, &lines);
101 	else if(nfiles>1) print("total", opt, chars, words, lines);
102 
103 	return 0;
104 }
105 
106 


hijacker
hijacker
hijacker
hijacker