I am trying to create a program that reads from a file and counts the occurrence of each alphabetic character in the file. Below is what I have so far, however the counts returned (stored in counters array) are higher than expected.
void count_letters(const char *filename, int counters[26]) {
FILE* in_file = fopen(filename, "r");
const char ALPHABET[] = "abcdefghijklmnopqrstuvwxyz";
if(in_file == NULL){
printf("Error(count_letters): Could not open file %s\n",filename);
return;
}
char line[200];
while(fgets(line, sizeof(line),in_file) != NULL){ //keep reading lines until there's nothing left to read
for(int pos = 0; pos < sizeof(line); pos++){//iterate through each character in line...
if(isalpha(line[pos])){//skip checking and increment position if current char is not alphabetical
for(int i = 0; i < 26; i++){//...for each character in the alphabet
if(tolower(line[pos]) == tolower(ALPHABET[i]))//upper case and lower case are counted as same
counters[i]++; // increment the current element in counters for each match in the line
}
}
}
}
fclose(in_file);
return;
}