Lex program to copy the content of one file to another file

Problem: Given a text file as input, the task is to copy the content of the given file to another file.

Explanation:
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.

Approach:
As we know, yytext holds the text matched by the current token. Append the value of yytext to a temporary string. If a newline character (‘\n’) is encountered, write the content of temporary string to destination file.

Input File: input.txt

GeeksForGeeks: A Computer Science portal for geeks.

Below is the implementation of above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

/* LEX code to replace a word with another 
   taking input from file */
    
/* Definition section */
/* character array line can be  
   accessed inside rule section and main() */
  
%{
#include<stdio.h>
#include<string.h>
char line[100];
  
%}
  
/* Rule Section */
/* Rule 1 writes the string stored in line 
   character array to file output.txt */
/* Rule 2 copies the matched token
   i.e every character except newline character
    to line character array  */
  
%%
['\n']    { fprintf(yyout,"%s\n",line);}
(.*)      { strcpy(line,yytext); }
%%
  
  
int yywrap()
{
    return 1;
}
  
/* code section */
int main()
{
        extern FILE *yyin, *yyout;
        /* open the source file 
           in read mode */
    yyin=fopen("input.txt","r");
  
          
        /* open the output file 
           in write mode */
    yyout=fopen("output.txt","w");
    yylex();
}

chevron_right


Output:





Output file: output.txt

GeeksForGeeks: A Computer Science portal for geeks.


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.