Skip to content
Related Articles

Related Articles

Improve Article

Lex program to take input from file and remove multiple spaces, lines and tabs

  • Last Updated : 30 Apr, 2019
Geek Week

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.

Prerequisite: FLEX (Fast Lexical Analyzer Generator)


hello      how


Welcome      to
Geeks    for


Open input file in read mode and whenever parser encounters newline (\n), space ( ) or tab (\t) remove it and write all the other characters in output file.

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

Below is the implementation program:

/*Lex program to take input from file and 
remove multiple spaces, newline and tab
and write output in a separate file*/
% {
    /*Definition section */
/* Rule: whenever space, tab or 
newline is encounterd, remove it*/
% %
[ \n\t]+ {fprintf(yyout, "");}
.       { fprintf(yyout, "%s", yytext); }
% %
int yywrap(){}
// driver code 
int main()
    /* yyin and yyout as pointer
    of File type */
    extern FILE *yyin, *yyout;
    /* yyin points to the file input.txt
    and opens it in read mode*/
    yyin = fopen("Input.txt", "r");
    /* yyout points to the file output.txt
    and opens it in write mode*/
    yyout = fopen("Output.txt", "w");
    return 0;


Take a step-up from those “Hello World” programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.
My Personal Notes arrow_drop_up
Recommended Articles
Page :