📜  LEX程序可将行号添加到给定文件

📅  最后修改于: 2021-05-26 02:05:27             🧑  作者: Mango

Lex是一个生成词法分析器的计算机程序,由Mike Lesk和Eric Schmidt编写。
Lex读取指定词法分析器的输入流,并输出以C编程语言实现词法分析器的源代码。

先决条件: Flex(快速词法分析器生成器)

例子:

Input:
#include
// Driver Code
int main()
{
int a; 
/* we have to delete comments */
return 0;
}

Output:
1 #include
2 // Driver Code
3 int main()
4 {
5 int a; 
6 /* we have to delete comments */
7 return 0;
8 }

方法:
由于/ n,遇到了新行。要计算行数,请在存在初始单行的情况下,将初始值为1时发生的/ n数进行计数。其他所有事情都可以忽略,因为重点是/ 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 .*\n    
  
%%
{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;
}

输出:

想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。