I'm trying to read out my text file line by line
FILE *infile;
char line[1000];
infile = fopen("file.txt","r");
while(fgets(line,1000,infile) != NULL)
{
//....
}
fclose(infile);
And then I need to find a specific word, for example "the", and need to see how many time it occurs and what lines it also occurs on.
I should be able to count the words with this
int wordTimes = 0;
if((strcmp("the", currentWord) == 0))
{
printf("'%s' appears in line %d which is: \n%s\n\n", "the", line_num, line);
wordTimes++;
}
where line
is the line of text that the string occurs on and line_num
is the line number that it occurs on.
And then the amount of times the word is shown uses this code:
if(wordTimes > 0)
{
printf("'%s' appears %d times\n", "the", wordTimes);
}
else
{
printf("'%s' does not appear\n", "the");
}
The problem is that I'm not sure how to compare each word in the line to "the" and still print out the line it applies on.
I have to use very basic C for this, so that means I can't use strtok()
or strstr()
. I can only use strlen()
and strcmp()
.