I'm trying to write a program that takes a file and a string by using Standard C functions, the program counts all the characters in the file which the string contains.
For example if the user writes:
counter.exe x.txt abcd
The program calculates the number of each character that the string contains: a, b ,c ,d in file x.txt
Sample message:
Number of 'a' characters in 'x.txt' file is: 12
Number of 'b' characters in 'x.txt' file is: 0
Number of 'c' characters in 'x.txt' file is: 3
Number of 'd' characters in 'x.txt' file is: 5
So far I've been able to make it print and count one character from the file, how do I make it count all the characters that I tell it to count, not just the first one from the string?
counter.c code:
#include<stdio.h>
int main() {
int count = 0;
char sf[20]; char rr; FILE* fp; char c;
printf("Enter the file name :\n");
gets(sf);
printf("Enter the character to be counted :\n");
scanf("%c", &rr);
fp = fopen(sf, "r");
while ((c = fgetc(fp)) != EOF)
{
if (c == rr)
count++;
}
printf("File '%s' has %d instances of letter '%c'.", sf, count, rr);
fclose(fp);
return 0;
}
#define SIZE 1024
char * malloc_buff(int dim){
char *buf;
buf=malloc(sizeof(char)*dim);
if(buf==NULL){
perror("Error in malloc");
}
return buf;
}
char * read_file(char * file){
FILE* fd;
char* file_pt;
file_pt=malloc_buff(SIZE);
errno=0;
fd=fopen(file,"r+");
if(errno!=0){
fprintf(stderr,"error open file\n");
exit(-1);
}
fread(file_pt,sizeof(char),SIZE,fd);
if(fclose(fd)){
fprintf(stderr,"errore close file\n");
exit(-1);
}
return file_pt;
}
int main(int argc, char *argv[])
{
char* content;
content=malloc_buff(SIZE);
content=read_file(argv[1]);
int lenght_word=strlen(argv[2]);
int counter[lenght_word];
int i=0,x=0;
for(x=0;x<lenght_word;x++){
counter[x]=0;
}
while (content[i]!='\0'){
for(x=0;x<lenght_word;x++){
if (content[i]==argv[2][x]){
counter[x]++;
}
}
i++;
}
for(x=0;x<lenght_word;x++){
printf("The values are: for %c is %d",argv[2][x],counter[x]);
}
return 0;
}