#include #include #include #include #include #include struct list { struct list *next ; char *name ; int counter; }; #define MAXWORD 100 #define HASHSIZE 101 typedef struct list list; list *hashtable[HASHSIZE]; // hashfunction of the hashtable unsigned hashfunc(char *s); list *lookup(char *s,list *hasht[]); list *insert(char *s,list *hasht[]); //duplicate of s char *strdup(char *s); // this function finds the next word int findword(FILE *fp, char *word, int lim); int findword(FILE *fp ,char *word, int lim) { int c ; char *w = word; while(isspace(c = getc(fp))) ; if (c != EOF) *w++ =c; if(!isalpha(c)) { *w = '\0'; return c; } for( ; --lim > 0 ; w++) if(!isalnum(*w = getc(fp))) { ungetc(*w, fp); break; } *w ='\0'; return word[0]; } char *strdup(char *s) { char *p; p=(char *) malloc(strlen(s)+1); if(p!=NULL) strcpy(p,s); return p; } unsigned hashfunc(char *s) { unsigned hashval; for(hashval = 0; *s!='\0' ; s++) hashval = *s + 31*hashval; return (hashval % HASHSIZE); } list *lookup(char *s,list *hasht[]) { list *np; for (np= hasht[hashfunc(s)]; np!=NULL; np=np->next) if(strcmp(s,np->name) == 0) return np; //found return NULL; // not found } list *insert(char *name,list *hasht[]) { list *np; unsigned hashval; if((np = lookup(name,hasht)) == NULL) { //not found np = (list *) malloc(sizeof(*np)); if(np==NULL || (np->name = strdup(name)) == NULL) return NULL; hashval = hashfunc(name); np->next = hasht[hashval]; hasht[hashval] = np; np->counter=1; } else np->counter++; return np; } main(int argc ,char *argv[]) { FILE *fp; char word[MAXWORD]; list *plist,*np; // list *hasht[HASHSIZE]; if (argc!=2) { printf("Error in using the program !"); printf("\n Usage : C:\ progname filename "); } if((fp=fopen(argv[1],"r"))==NULL) { printf("cannot open file\n"); exit(1); } // hashtable=( list* ) NULL; while(findword(fp,word,MAXWORD) != EOF) if(isalpha(word[0])) plist= insert(word,hashtable) ; for(int i=0; i<101 ; i++) for (np= hashtable[i]; np!=NULL; np=np->next) { if(np!=NULL) { cout<<"The word : " << np->name<<" appeared " ; cout << np->counter<<" times. \n"; } } }