http://i.imgur.com/suOkCLh.png Write a C program named as getMostFreq.c that tak
ID: 3574632 • Letter: H
Question
http://i.imgur.com/suOkCLh.png
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.Explanation / Answer
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[] )
{
FILE *fp;
if( access(argv[1], F_OK ) != -1 )
{
fp = fopen(argv[1],"r");
}
else
{
printf("Error: File does not exist. ");
return 0;
}
char ch;
int ct[26],i,j,max;
for(i=0;i<26;i++)
{
ct[i]=0;
}
max=0;
while(fscanf(fp,"%c",&ch)!=EOF)
{
if(ch>='a' &&ch<='z')
{
ct[ch-'a']++;
if(ct[ch-'a']>ct[max])
{
max = ch-'a';
}
}
else if(ch>='A' &&ch<='Z')
{
ct[ch-'A']++;
if(ct[ch-'A']>ct[max])
{
max = ch-'A';
}
}
}
printf("The most frequent letter is '%c',it appeared %d times ",max+'a',ct[max]);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.