There are some problems with the above examples that should be pointed out.
>char *word,*searchStr;
>int no_of_word=0,i=0;
>FILE *fp;
>gets(searchStr);
Three errors here. No memory for searchStr is allocated, so gets() will write into unitialized memory, No memory is allocated for word which is used later in the example and any use of gets() is a bug because the programmer can't place a limit on the number of characters entered by the user. Instead, something like this:
char searchStr[50]; /* 50 or whatever */
if (fgets(searchStr,sizeof searchStr,stdin)!=NULL) {
/* ... */
Or if you want to use pointers:
char *searchString=malloc(51); /* allocate for 50 characters */
if (searchStr!=NULL) {
if (fgets(searchStr,51,stdin)!=NULL) {
/* ... */
Of course, 50 should be replaced with a symbolic constant or be stored as a variable.
Next example:
>char *word;//this is the search string
>char *string;//this is the string from the file
>FILE *f;
>int number=0;
>printf("Please enter the word to search):
>scanf("%s",word);
Same thing here, scanf() writes into unitialized memory because word doesn't point anywhere valid. Also, there is no limit placed on the number of characters you can enter, as in gets().
Either:
char word[50];
scanf("%50s",word);
Or just use fgets().
>while(!feof(f))
The problem is that feof() tests the stream *before* it's been evaluated, so the fscanf() call will hit EOF before the above line will detect it.
> {
> fscanf(f,"%s",string);
No memory has been allocated for string, so it points somewhere random. Also, since the fscanf() return value isn't checked, we don't know what the status of string is for the next line (even if it did point to valid memory).
> if(!strcmp(string,word))//if match found
> number++:
> }
Russ
bobbitts@hotmail.com