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

Write a C program named as getMostFreq.c that takes input text file as arguments

ID: 3576214 • Letter: W

Question

Write a C program named as getMostFreq.c that takes input text file as arguments, outputs the most frequent letter (ignoring cases) and displays how many times that letter appears. If the text file does not exist, print out an error message to the terminal. For example, sample outputs could be like below $cat test.txt This is a list of courses. CSC 1010 - COMPUTERS & APPLICATIONS $./countC test.txt Most frequent letter is 's', it appeared 8 times $./countC NotExist.txt Error: file not exist. Put the source code of getMostFreq.c in your answer sheet. In your answer sheet, please also attach screenshots of the outputs using the test.txt file in the example.

Explanation / Answer

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define size 10000

/* structure holding wordcount frequency information */

typedef struct _wordcount {
char word[100]; /* the wordcount */
int count; /* number of times wordcount occurs */
} wordcount;


void prepareList (wordcount *wordcounts, int *n, char *wordfromfile) {
int i;

/* linear search for the wordcount */
for (i=0; i<*n; i++)
if (strcmp (wordfromfile, wordcounts[i].word) == 0) {

wordcounts[i].count++;
return;
}


wordcounts[*n].word= wordfromfile;

wordcounts[*n].count = 1;

(*n)++;
}

int compareWordCounts (wordcount *first, wordcount *second) {
if (first->count < second->count) return +1;
if (first->count > second->count) return -1;
return 0;
}

/* main program */
int main (int argc, char **argv) {
wordcount wordcounts[size];
char s[100];
int i, n, m;

n = 0;

/* read all the words in the file... */

   FILE *fileHandle;
  
   if((fileHandle = fopen(argv[1], "r")) == NULL){
       printf("Error : file doesnot exist !!");
       return -1;
   }

   char *word = NULL;
   while(fgets(line,size,fileHandle) != NULL)
   {
       word = strtok(line," ");
        while(p != NULL)
        {
prepareList(wordcounts, &n, tolower(word));
        }
   }

/* sort descending */

qsort((void *) wordcounts, n, sizeof (wordcount),
(int (*) (const void *, const void *)) compareWordCounts);

printf ("%s %d ", wordcounts[0].word, wordcounts[0].count);
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote