Lex program to search a word in a file

Problem: Write a Lex program to search a word in a file.

Explanation:
FLEX (Fast Lexical Analyzer Generator) is a tool/computer program for generating lexical analyzers (scanners or lexers) written by Vern Paxson in C around 1987. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language. The function yylex() is the main flex function which runs the Rule Section.

Examples:

Input: welcome to geeksforgeeks 
Output: welcome 
FOUND
 
for 
NOT FOUND

geeksforgeeks
FOUND 

Approach:
To search a word, I have stored words in file named “input.txt” and used lex to receive words from keyboard. On receiving each word, I check it with the words in the file. If the word is found, the program prints “FOUND” else “NOT FOUND”.

Input File: input.txt (Input File used in this program)

Below is the implementation of program:

filter_none

edit
close

play_arrow

link
brightness_4
code

/* Lex program to search a word in a file */
  
%{
 /* Definition section */
#include<string.h>
void check(char *);
%}
  
/* Rule Section */
%%
[a-zA-Z]+ check(yytext);
%%
  
// driver code
int main()
{
    // The function that starts the analysis 
    yylex();
    return 0;
}
void check(char *str)
{
      /* fp as pointer 
    of File type */
    FILE *fp;
    char temp[30];
     
       
    /* fp points to the file input.txt 
    and opens it in read mode */
    fp=fopen("input.txt", "r");
    while((fscanf(fp, "%s", temp))!=EOF)
    {
        if(!(strcmp(temp, str)))
        {
            printf("FOUND\n");
            return;
        }
         
    }
    printf("NOT FOUND\n");
        return;
}

chevron_right


Output:



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.