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
w3wiki: A Computer Science portal for Beginner.
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);} <<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
w3wiki: A Computer Science portal for Beginner.