Write a C program named as countD.c that takes input text file and a digit as ar
ID: 3822769 • Letter: W
Question
Write a C program named as countD.c that takes input text file and a digit as arguments, outputs how many times the digit appears in the file.
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
$./countD test.txt
1 '1' appeared 2 times
$./countD NotExist.txt 1
Error: file not exist.
Hint: you may need to refer to one example getMostFreq.c in iCollege.
Please find it in Course Content -> Program Challenges -> PC9
Explanation / Answer
The file takes the text file and the digit as command line arguments,arc indicates the count and argv array contains the argments,first one being the file name and second one digit.
here we are not comparing the ascii value just character comparision is done for a match.so digit is also taken as a character.
First open the file in read mode,scan the file by character by character and compare it with the digit,if a match is found increase the count of occurences,if the count is zeri no match occurs and error is printed.
#include<stdio.h>
#include<stdlib.h>
#include<String.h>
int main(int argc,char *argv[]) {
int x;
if(argc<3||argc>3) {
exit(1);
}
x=count(argv[1],argv[2]);
if(x==0){
perror("error");
exit(1);
}
else {
printf(" the number of occurences are %d",x);
}
return(0);
}
-->int count(char*file ,char*str)
{
char c;
int n=0;
FILE *fp =fopen( argv[1],'r');
while((fread(&c,sizeof(char),1,fp))!=0)
{
if(c=='str')
{
n++;
}
}
fclose(fp);
return n;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.