home *** CD-ROM | disk | FTP | other *** search
- /**************************************************************************
- * WORDCNT.C -- a very dumb word and line counter by
- * James W. Birdsall
- * version 1.0 3/13/89
- *
- * usage: wordcnt filename
- *
- * This program is a memory hog. In order to avoid thrashing the drive,
- * especially on large files, the program reads the entire file into
- * memory. The entire file must fit into memory -- there is no provision
- * made for partial reads. Maybe in the next version...
- */
-
-
- #include <stdio.h>
- #include <alloc.h>
- #include <ctype.h>
- #include <dos.h>
-
- #define INWORD 1
- #define INSPACE 0
- #define HOLDINGSIZ 32000
-
-
- main(int argc, char *argv[])
- {
- FILE *infile;
- char huge *temp, huge *temp3;
- char holding[HOLDINGSIZ];
- long words = 0;
- long lines = 0;
- long length, temp2;
- int readtemp;
- long readchar = 0;
- short state;
- short oldstate;
-
-
- /* check usage */
- if (argc < 2) {
- printf("Usage: wordcnt filename\n");
- exit(3);
- }
- /* open the file */
- if (!(infile = fopen(argv[1],"rt"))) {
- printf("Error opening file %s\n", argv[1]);
- exit(3);
- }
- /* the simple way of finding the size of the file */
- /* actually, this tends to overestimate the file size because text files */
- /* are saved using CR/LF pairs and are read into memory using only LF's */
- /* so two bytes appear in the filesize for every newline and only one is */
- /* actually used */
- if (fseek(infile, 0L, SEEK_END)) {
- printf("Error scanning file\n");
- exit(3);
- }
- if ((length = ftell(infile)) == -1) {
- printf("Error scanning file\n");
- exit(3);
- }
- /* reset to the beginning of the file */
- if (fseek(infile, 0L, SEEK_SET)) {
- printf("Error scanning file\n");
- exit(3);
- }
- /* grab memory */
- if (!(temp = (char huge *) farmalloc(length))) {
- printf("File too big\n");
- exit(3);
- }
- temp3 = temp;
- /* read into memory */
- do {
- /* read into near memory */
- if (!(readtemp = fread(holding, sizeof(char), HOLDINGSIZ, infile))) {
- printf("Error reading file\n");
- exit(3);
- }
- /* move to far memory */
- movedata(_DS, holding, FP_SEG(temp3), FP_OFF(temp3), readtemp);
- temp3 += readtemp;
- readchar += readtemp;
- } while (readtemp == HOLDINGSIZ);
- /* close file */
- if (fclose(infile)) {
- printf("Error closing file\n");
- exit(3);
- }
- /* count words -- counter is incremented upon transition from word (alpha */
- /* and digits) to space (anything else) */
- state = INSPACE;
- oldstate = INSPACE;
- temp3 = temp;
- for (temp2 = 0; temp2 < readchar; temp2++, temp3++) {
- if (isalnum(*temp3))
- state = INWORD;
- else {
- if (*temp3 == '\n')
- lines++;
- state = INSPACE;
- }
- if (state == INSPACE && oldstate == INWORD)
- words++;
- oldstate = state;
- }
- /* printout and exit */
- printf("%ld words on %ld lines found in file %s\n", words, lines, argv[1]);
- farfree(temp);
- exit(0);
- }
-
-