Why are you opening the text file, in append+ mode?
Aren't you just reading the file, from first word to last word?
This is what I think you were setting out to do with your program.
Code:
#include <stdio.h>
#include <string.h> //strlen()
#include <ctype.h> //isalpha()
int main (void)
{
//declare
FILE * cfile;
char ch;
int len, j, i = 0;
int count = 0;
char target[20]; //the word we are looking for
char mystring[20] = { '\0' }; //the word from the file
/*************************************************************
working with arrays and strings
*************************************************************/
printf("\n\n\n\n"); //clean some space
/*************************************************************
find file, write to it, output the string, end and close file
**************************************************************/
//define and open text file
cfile = fopen("blessing.txt", "rt");
//error handling if file does not exist
if(cfile == NULL) printf("Cannot open file");
// input target
printf("Enter the target word I'm looking for: ");
fgets(target, sizeof(target), stdin);
printf("\nTarget: %s", target);
//remove the newline fgets() adds, replace it with EOS char
target[strlen(target) - 1] = '\0';
for(i = 0; i < strlen(target); i++) //convert target to all lowercase
{
if(target[i] >= 'A' && target[i] <='Z')
target[i] = target[i] + 32;
}
printf("\ntarget: %s", target);
/*************************************************************
parse through file and search for string
**************************************************************/
i = 0; //prime the while "pump"
while(1) {
ch=fgetc(cfile);
if(ch == EOF)
break;
if(isalpha(ch)) {
mystring[i] = ch;
++i;
}
else { //we should be at the end of the word
//so set mystring's word, to all lowercase
len = strlen(mystring);
if(len == 0)
continue;
for(j = 0; j <= len; j++) {
if(mystring[j] >= 'A' && mystring[j] <= 'Z')
mystring[j] += ('a' - 'A');
}
//add the end of string char
mystring[i+1] = '\0';
//show nothing is going awry :)
printf("\n mystring: %s", mystring);
//see if the words are a match and count 'em up, if they are.
if((strcmp(mystring, target)) == 0)
count++;
//remove the old word
for(i = 0; i <= len; i++)
mystring[i] = '\0';
i = 0; //reset i for the next word
}
}
//close file
fclose(cfile);
//show user file has been written
//printf("\nSuccess. File has been written\n");
printf("\n\nYour search '%s' was found %d times \n", target, count);
printf("Press Enter to Continue...");
j = getchar();
return 0;
}
I used this phrase, in the file "blessing.txt":
"For food, for raiment, for life and opportunity; for friendship and fellowship, we thank Thee, oh Lord."
It works properly, in limited testing.