/* * wc [file ...] */ /*)BUILD $(TKBOPTIONS) = { TASK = ...WCX } */ #ifdef DOCUMENTATION title wc Word Count index Count Words, Lines, and Bytes in Files synopsis wc [name ...] description Count the number of bytes, words, and lines in one or more files. wc accepts wild-card file name arguments. diagnostics .lm +8 .s.i -8;"file name": cannot open .s.i -8;"file name": illegal file name .lm -8 author Martin Minow bugs #endif #include long twords = 0; long tlines = 0; long tbytes = 0; char file_name[81]; main(argc, argv) char *argv[]; { register int i, nfiles; register FILE *fp; int gotcha; nfiles = 0; if(argc < 2) { ++nfiles; count(stdin, NULL); } else { #ifdef unix for (i = 1; i < argc; ++i) { if ((fp = fopen(argv[i], "r")) == NULL) { perror(argv[i]); } else { ++nfiles; count(fp, argv[i]); fclose(fp); } } #else for (i = 1; i < argc; ++i) { if ((fp = fwild(argv[i], "r")) == NULL) { perror(argv[i]); } else { for (gotcha = 0; fnext(fp) != NULL; gotcha++) { ++nfiles; fgetname(fp, file_name); count(fp, file_name); } if (gotcha == 0) fprintf(stderr, "\"%s\": no matching files\n", argv[i]); } } #endif } if (nfiles > 1) output(tlines, twords, tbytes, "total"); } count(fp, filename) FILE *fp; /* File pointer */ char *filename; /* File name string */ { register int c, inword; long lines; long words; long bytes; lines = 0; words = 0; bytes = 0; inword = 0; while((c = getc(fp)) != EOF) { ++bytes; if (c == ' ' || c == '\t' || c == '\n') { inword = 0; if (c == '\n') ++lines; } else if (!inword) { ++inword; ++words; } } twords += words; tlines += lines; tbytes += bytes; output(lines, words, bytes, filename); } output(lines, words, bytes, filename) long lines; long words; long bytes; char *filename; { plural(lines, "line"); plural(words, "word"); plural(bytes, "byte"); if (filename != NULL) printf(" %s", filename); printf("\n"); } plural(value, what) long value; char *what; { #ifdef unix printf(%8ld", value); #else printf("%8ld %s%c", value, what, (value == 1) ? ' ' : 's'); #endif }