Skip to content
Related Articles

Related Articles

Improve Article

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

  • Difficulty Level : Medium
  • Last Updated : 07 Apr, 2021

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:
 

C




/* 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); line[0] = '\0'; }
<<EOF>> { fprintf(yyout,"%s",line); return 0;}
%%
 
 
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();
}

Output:
 



Output file: output.txt 
 

GeeksForGeeks: A Computer Science portal for geeks.

 

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :