Lex program to copy the content of one file to another file
Last Updated :
21 Feb, 2023
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
%{
#include<stdio.h>
#include<string.h>
char line[100];
%}
%%
[ '\n' ] { fprintf (yyout, "%s\n" ,line);}
(.*) { strcpy (line,yytext);}
<<EOF>> { fprintf (yyout, "%s" ,line); return 0;}
%%
int yywrap()
{
return 1;
}
int main()
{
extern FILE *yyin, *yyout;
yyin= fopen ( "input.txt" , "r" );
yyout= fopen ( "output.txt" , "w" );
yylex();
}
|
Output:
Output file: output.txt
GeeksForGeeks: A Computer Science portal for geeks.
Share your thoughts in the comments
Please Login to comment...