Advertisement
Broatlas

wordcount

Apr 13th, 2016
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.75 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4.  
  5. #define VALID_ARGS 2
  6. #define MAX_WORD 45
  7. #define ARGS "FILENAME"
  8.  
  9. int main(int argc, char *argv[]){
  10.   int count = 0;
  11.   int wcount = 0;
  12.   char *line;
  13.   FILE *fp;
  14.   if(argc != VALID_ARGS){
  15.     printf("%s %s\n",argv[0], ARGS );
  16.     exit(EXIT_FAILURE);
  17.   }
  18.   if((fp = fopen(argv[1], "r")) == NULL) {
  19.     perror("fopen");
  20.     exit(EXIT_FAILURE);
  21.   }
  22.   if((line = (char *)malloc (sizeof(char) * MAX_WORD)) == NULL){
  23.     perror("malloc line");
  24.     exit(EXIT_FAILURE);
  25.   }
  26.   while((fgets(line, MAX_WORD, fp)) != NULL){
  27.     line[strlen(line)-1] = '\0';
  28.     printf("%s:%d\n",line, strlen(line));
  29.     count += strlen(line);
  30.     wcount++;
  31.   }
  32.   printf("total wordcount: %d\n", wcount);
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement