Reputation: 77
I'm attempting to create a program that lets the user enter words and then the program searches the file for the entered word. I believe what happens in my program however is that as I enter the words it doesn't start over at 0 of the char array I'm entering it into
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int num =0;
char word[2000];
char *string;
FILE *in_file = fopen("words.txt", "r");
//FILE *out_file = fopen("output.txt", "w");
if (in_file == NULL)
{
printf("Error file missing\n");
exit(-1);
}
while(word[0]!= '0')
{
printf("please enter a word(enter 0 to end)\n");
scanf("%s",word);
while(!feof(in_file))
{
fscanf(in_file,"%s",string);
if(!strcmp(string,word))//if match found
num++;
}
printf("we found the word %s in the file %d times\n",word,num );
num = 0;
}
return 0;
}
Can someone help me so that it rereads into the correct position? So that when it goes to compare the words it does so correctly?
Upvotes: 3
Views: 7832
Reputation:
You forgot to declare memory for char *string;
. Your program tries to write with fscanf(in_file,"%s",string);
in unreserved memory causing undefined behavior and then very likely a crash.
Replace char *string;
with char string[ MAX_WORD_LENGTH ]
There are many other problems, for example your search might only work on the first try since you are reading the file every time and once you hit EOF you won't read any more. You should set the position indicator to the beginning of the file with fseek on every search.
fseek ( in_file, 0, SEEK_SET );
Also using strstr instead of strcmp might produce better results.
Upvotes: 2