Hello friends, I am having a problem writing a function to search for a string in an input file. I have successfully output the file with line numbers, which was the first step in the program, but now I am stuck on searching for a given string. After searching for the string I want to print the number of times it appears in the input file. As of right now all the function does is return a junk number. I have tried many different things and haven't gotten anything to work correctly.
Here is my code
#include <stdio.h>
#include <string.h>
#define MAX 1000
void find_string(char text[], char pattern[]);
int main()
{
char pattern[] = "of"; //string to search for
int counter = 0;
static const char filename[] = "in.txt";
FILE *file = fopen(filename, "r");
if ( file != NULL )
{
char line [ MAX ];
while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
{
++counter;
printf( "%d ", counter);
fputs ( line, stdout ); /* write the line */
}
printf( "\n\n");
find_string(filename, pattern);
fclose ( file );
}
else
{
perror ( filename );
}
char wait;
scanf( "%c", &wait );
return(0);
}
void find_string(char text[], char pattern[])
{
int matches;
static const char filename[] = "in.txt";
FILE *file = fopen(filename, "r");
if ( file != NULL )
{
char line [ MAX ];
while ( fgets ( line, sizeof line, file ) != NULL )
{
if( line == pattern)
matches++;
}
printf("%d", matches);
}
}
Thanks to anyone who takes the time to point me in the right direction.
I attached the input file as an attachment.
Thanks again for any help.