find a word in a file in c code example
Example 1: search a word in a string in c
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
int main()
{
char str[MAX_SIZE];
char word[MAX_SIZE];
int i, j, found;
printf("Enter any string: ");
gets(str);
fflush(stdin);
printf("Enter any word to search: ");
gets(word);
for(i=0; i<strlen(str) - strlen(word); i++)
{
found = 1;
for(j=0; j<strlen(word); j++)
{
if(str[i + j] != word[j])
{
found = 0;
break;
}
}
if(found == 1)
{
printf("'%s' found at index: %d \n", word, i);
}
}
return 0;
}
Example 2: how to search in a file in c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int num =0;
char word[2000];
char *string[50];
FILE *in_file = fopen("student.txt", "r");
if (in_file == NULL)
{
printf("Error file missing\n");
exit(-1);
}
while(student[0]!= '0')
{
printf("please enter a word(enter 0 to end)\n");
scanf("%s", student);
while(!feof(in_file))
{
fscanf(in_file,"%s", string);
if(!strcmp(string, student))==0
num++;
}
printf("we found the word %s in the file %d times\n",word,num );
num = 0;
}
return 0;
}