Lex是一个生成词法分析器的计算机程序,由Mike Lesk和Eric Schmidt编写。 Lex读取指定词法分析器的输入流,并输出用C编程语言实现该词法分析器的源代码。
null
先决条件: Flex(快速词法分析器生成器)
例子:
Input: #include<stdio.h> // Driver Code int main() { int a; /* we have to delete comments */ return 0; } Output: 1 #include<stdio.h> 2 // Driver Code 3 int main() 4 { 5 int a; 6 /* we have to delete comments */ 7 return 0; 8 }
方法: 由于 /n .要计算行数,请计算行数 /n 初始值为1时发生,因为存在初始单行。所有其他的事情都可以忽略,因为重点是数量 /n .将计数器初始设置为1,并在出现新行(/n)时递增。
输入文件:testtest。C
下面是向给定文件添加行号的实现。
/* Program to add line numbers to a given file*/ %{ int line_number = 1; // initializing line number to 1 %} /* simple name definitions to simplify the scanner specification name definition of line*/ line .* % {line} { printf ( "%10d %s" , line_number++, yytext); } /* whenever a line is encountered increment count*/ /* 10 specifies the padding from left side to present the line numbers*/ /* yytext The text of the matched pattern is stored in this variable (char*)*/ % int yywrap(){} int main( int argc, char *argv[]) { extern FILE *yyin; // yyin as pointer of File type yyin = fopen ( "testtest.c" , "r" ); /* yyin points to the file testtest.c and opens it in read mode.*/ yylex(); // The function that starts the analysis. return 0; } |
输出:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END