function to count words

we are working with threads, and have to write a program that counts the number of words in an arbitrary number of files, one thread per file. The thread part works fine..the problem is in the little function that counts the words. It is counting the total characters in the files instead of the words.
here it is, any suggestions would be appreciated. I think I have stared at it for too long and might be overlooking something silly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void* count_words(void* f)
{
  char* filename = (char*) f;
  FILE *FP; 
  char c, prevc = '\0';
  if ((FP=fopen(filename,"r"))!=NULL)	  
	  {
		 while(c=fgetc(FP)!=EOF)
		 {
						
			if(!isalnum(c)&&!isalnum(prevc))
			{
	                         pthread_mutex_lock(&lock);
		                 counter++;
				 pthread_mutex_unlock(&lock);
			}
			prevc=c;
		}
			
			fclose(FP);
	}
	else perror("exit");
	return NULL;

}
How about a function that reads and ignores characters until it reaches a whitespace, at which point it increments a counter by one? The counter must start from 1.

Recommendation for this: Use <string.h>.

-Albatross

P.S.-There are more reliable ways to count words, but this is just to get your frontal lobes pointing in the right direction.
Last edited on
Present version of count_words counts number of fragments separated by two not alphanumeric elements. For example, , or . . To calculate words, condition

 
if (!isalnum(c)&&!isalnum(prevc))


should be modified. Usually, words are separated by a whitespace. So, just modify above condition.

PS. I wonder HOW it calculates number of characters.
Topic archived. No new replies allowed.