Originally Posted by
panosstylianou
Is there a way i can compare the words from the dictionary file itself? i tried copying the whole dictionary in an array but something seems to be wrong with my code.
Why do you copy the entire filecontent?
File- and string handling are easy in C,
- calculate the max. wordlen
- allocate one memoryblock
- read each word in
- sort them
- (b)search them
No pointerarray or realloc stuff is needed like:
Code:
int main()
{
size_t maxlen=0,z=0;
FILE *f=fopen("words.txt","r");
char line[100],*words,*p;
while( fgets(line,100,f) ) /* read each line with one word */
{
if( strlen(line)>maxlen ) maxlen=strlen(line);
++z;
}
p=words=malloc(z*++maxlen); /* allocate the needed memory as one block */
rewind(f); /* to filebegin */
while( fgets(line,100,f) ) /* read each line with one word */
{
if( strchr(line,'\n') ) *strchr(line,'\n')=0;
strcpy(p,line);
p+=maxlen;
}
fclose(f);
qsort(words,z,maxlen,strcmp); /* sort all words asc */
printf("searchword:");
scanf("%99s",line); while(getchar()!='\n');
if( bsearch(line,words,z,maxlen,strcmp) ) /* search for your word */
puts("found");
else
puts("not found");
free(words);
return 0;
}
You can replace strcmp with other functions like stricmp, soundex or what you need.