I am trying to write a program for searching strings(one at a time)in a text file.
To start things off, I wrote this one.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
FILE *txt_file;
int chr;/*char read by fgetc*/
int word_match=0;
const char* substring ="window";/*search word*/
int i=0;
char word[15];/*to save the word read from the file)*/
if((txt_file=fopen("text.txt","r"))==NULL)
{
printf("Can't open the file\n");
exit(1);
}
while((chr=fgetc(txt_file))!=EOF)
{
word[i]= chr;
i++;
if(isspace(chr)||ispunct(chr))
{
word[i-1]='\0';
/* printf("%s\n",word);/*testing! testing!*/
if(strcmp(word,substring)==0 )
{
word_match++;
}
i=0;
}
if(isspace(word[i]))
i=0;
}
fclose(txt_file);
printf("Matched words:%d\n",word_match);
return EXIT_SUCCESS;
}
This program has got some limitations and is very inefficient too.
I'm looking for suggestions to make it a real world string searching program.
Note:Toggle plain text and copy it somewhere else If it's too hard to read due to indention.