The snippets below are from my program that gets words, then prints them with the number of occurences.
It works almost fine - it "forgots" that that entry has been saved before and does NOT increment counter associated with that. So I get eg. we - 1 we - 1 we - 1 instead of we - 3.
Code:
typedef struct {
char *word;
int occ;
}
words;
words *data=NULL;
Code:
words *findword(char *word)
{
words *ptr = data;
if ((strcmp(word, ptr->word)) != 0)
return ptr;
return NULL;
}
Code:
int main(int argc, char **argv)
{
char *word;
words *temp;
int c,i,num;
FILE *infile;
words *ptr = NULL;
if(argc!=2)
{ }
if((infile=fopen(argv[1],"r"))==NULL)
{ }
num=0;
data = malloc(sizeof(words));
data->word = "";
data->occ = 0;
while(1)
{
c=fgetc(infile);
if(c==EOF) break;
if(!isalpha(c)) continue;
else ungetc(c,infile);
word=getword(infile);
if(findword(word))
{
if(!(temp=realloc(data,sizeof(words)*(num+1))))
{ }
else
data=temp;
ptr = findword(word);
data[num].word=strdup(word);
data[num].occ=1;
num++;
}
else
ptr->occ++;
free(word);
}
/* sort procedure here, irrelevant for the purpose of topic */
for(i=0;i<num;i++)
{
printf("%s - %d\n",data[i].word,data[i].occ);
free(data[i].word);
}
free(data);
if(fclose(infile))
{/* error handling */ }
return 0;
}
What's wrong with that code?
Thanks in advance!