@gnometorule was correct. You're reading one more time than you need to. If you checked your return value, you would find fscanf
probably returned EOF
. What you want to do is read the file as long as fscanf
returns an expected value. Since you are reading 1 item, it should return 1. If it doesn't, there is a problem. Moreover, feof
will only be true if the end of the file was reached. What if there was a read error? You may be trying to read from a file that has its error indicator set, and feof
won't detect that.
Review the following code. It should give you an idea of how to handle files.
/* This is used to determine whether an end-of-file error message should be printed or the word was found. */
int cmp_result;
/* Stop reading when the file can't be read or the words are equal. */
do
cmp_result = strcmp(word, wd);
while (fscanf(f, "%s", wd) == 1 && cmp_result != 0);
/* Check for a file read error. */
if (ferror(f))
printf("Error reading file\n");
/* End of file reached before words are equal; feof(f) may be true when cmp_result==0 or not, so checking cmp_result is more reliable in this case. */
else if (cmp_result != 0)
printf("Word '%s' not found\n", word);
/* Words are equal. */
else
printf("Yes\n");
The logic is that if the loop was exited, there was a read error or the word was found. The branching statements after the loop test this.
First, the file's error indicator is checked. If it isn't set, the end of the file was reached, or the word was found.
If the word was found, the end of file indicator may be set or not. But if the word wasn't found, the end of file indicator must be set, else the loop wouldn't have exited since we already ruled out the error indicator in the first if statement. This is why we check the comparison result instead of using feof(f)
.
If those cases fail, we are left with one possibility: the word was found.
I hope this helps!