home *** CD-ROM | disk | FTP | other *** search
/ Power-Programmierung / CD1.mdf / magazine / pctchnqs / 1991 / number3 / l2.c < prev    next >
Text File  |  1991-05-28  |  2KB  |  59 lines

  1. /* Word counting program incorporating assembly language. Tested
  2.    with Borland C++ 2.0 in C compilation mode & the small model */
  3.  
  4. #include <stdio.h>
  5. #include <fcntl.h>
  6. #include <sys\stat.h>
  7. #include <stdlib.h>
  8. #include <io.h>
  9.  
  10. #define BUFFER_SIZE  0x8000   /* largest chunk of file worked
  11.                                  with at any one time */
  12. int main(int, char **);
  13. void ScanBuffer(char *, unsigned int, char *, unsigned long *);
  14.  
  15. int main(int argc, char **argv) {
  16.    int Handle;
  17.    unsigned int BlockSize;
  18.    long FileSize;
  19.    unsigned long WordCount = 0;
  20.    char *Buffer, CharFlag = 0;
  21.  
  22.    if (argc != 2) {
  23.       printf("usage: wc <filename>\n");
  24.       exit(1);
  25.    }
  26.  
  27.    if ((Buffer = malloc(BUFFER_SIZE)) == NULL) {
  28.       printf("Can't allocate adequate memory\n");
  29.       exit(1);
  30.    }
  31.  
  32.    if ((Handle = open(argv[1], O_RDONLY | O_BINARY)) == -1) {
  33.       printf("Can't open file %s\n", argv[1]);
  34.       exit(1);
  35.    }
  36.  
  37.    if ((FileSize = filelength(Handle)) == -1) {
  38.       printf("Error sizing file %s\n", argv[1]);
  39.       exit(1);
  40.    }
  41.  
  42.    CharFlag = 0;
  43.    while (FileSize > 0) {
  44.       FileSize -= (BlockSize = min(FileSize, BUFFER_SIZE));
  45.       if (read(Handle, Buffer, BlockSize) == -1) {
  46.          printf("Error reading file %s\n", argv[1]);
  47.          exit(1);
  48.       }
  49.       ScanBuffer(Buffer, BlockSize, &CharFlag, &WordCount);
  50.    }
  51.  
  52.    /* Catch the last word, if any */
  53.    if (CharFlag) {
  54.       WordCount++;
  55.    }
  56.    printf("\nTotal words in file: %lu\n", WordCount);
  57.    return(0);
  58. }
  59.