Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

C Programming: Compose some program that counts the words in a given file. -The

ID: 642561 • Letter: C

Question

C Programming:

Compose some program that counts the words in a given file.

-The name of the file to count the words in will be passed on the command line

-For this problem we will define a word as a series of 1 or more non-whitespace characters

     Use isspace to determine if a character is white space or not

Examples
Assume we have file named cool.txt that contains the following:

Computer sciences classes are great!

Even though I spend all my time doing homework :( 1../wcount cool.txt

There are 15 word(s) in fun.txt

Explanation / Answer

The program would look something like this

#include <stdio.h>
#include <stdlib.h>
int isSpace(char ch){ // Function to check if a given character is a space
    if(ch==' ')
        return 1;
    else
        return 0;
}
int main(int argc, char *argv[]){
   if(argc != 2){ //check if there are exactly two arguments. One the name of this c file and the other the file to be read
      printf("Please pass a single file name to read");
      exit(EXIT_FAILURE);
   }
   char characterreadFromFile;
   FILE *inputfile; // will be used to read the contents of the file
   inputfile = fopen(argv[1],"r"); // argv[1] contains the file name

   if( inputfile == NULL )
   {
       //Either the file does not exist or is not readable
      perror("Error while opening the file. ");
      exit(EXIT_FAILURE);
   }

   int wordCount = 0,readingAWord=0; //initially there are 0 words

   while( ( characterreadFromFile = fgetc(inputfile) ) != EOF ){ // read till the end of file or EOF is read
      if(isSpace(characterreadFromFile)){
            //a space is encountered meaning the word is no longer being read.
        readingAWord = 0;
        continue;
      }
      if(characterreadFromFile == ' '){
          //a new line is encountered meaning the word is no longer being read.
        readingAWord = 0;
        continue;
      }
      //if a word is being read, it continues to read the file
      if(!readingAWord){
          //if there was no word being read, we found a new word beginning. So we set readingAWord indicator as 1 and increase the word count
        readingAWord = 1;
        wordCount++;
        continue;
      }
   }
printf("There are %d word(s) in %s",wordCount,argv[1]);
   fclose(inputfile);
   return 0;
}


I have commented the program at places. Still if anything is unclear or you have any dounts, feel free to contact. Hope this helps :)