Counting words in a file in C
I am writing a function that counts the number of words in a file. Words can be separated by any number of whitespace characters. There can be integers in the file, but the program should only consider words that have at least one alphabetic character.
int word_count(const char *filename)
{
int ch;
int state;
int count = 0;
FILE *fileHandle;
if ((fileHandle = fopen(filename, "r")) == NULL){
return -1;
}
state = OUT;
count = 0;
while ((ch = fgetc(fileHandle)) != EOF){
if (isspace(ch))
state = OUT;
else if (state == OUT){
state = IN;
++count;
}
}
fclose(fileHandle);
return count;
}
I figured out how to deal with spaces, but I don't know how not to count combinations that do not have at least one alphabetic character (I know about isalpha and isdigit, but I have a hard time figuring out how to use them in my case).
I am very grateful for your help.
+3
source to share