FLEX&BISON:去除C代码注释和其中的多余空行

来源:互联网 发布:数据结构图的遍历代码 编辑:程序博客网 时间:2024/06/05 19:30

使用两个flex程序来完成。

去除注释flex代码文件flex1:

%option noyywrap%x COMMENT%{%}%%"//".* {}"/*" {BEGIN COMMENT;}<COMMENT>"*/" {BEGIN INITIAL;}<COMMENT>. {}. {printf("%s", yytext);}%%int main(int argc, char *argv[]){    const char *input_filename = "input";    if (argc == 2){         input_filename = argv[1];    }       yyin = fopen(input_filename, "r");    yylex();    fclose(yyin);    return 0;}

去除多余空行(连续的多行空行会被合并为一个空行)代码文件flex2

%option noyywrap%x COMMENT%{int num_newline = 0;%}%%^[ \t\n]+ {if (num_newline == 0){++num_newline; printf("\n");}}. {printf("%s", yytext); num_newline = 0;} %%int main(int argc, char *argv[]){    const char *input_filename = "input";    if (argc == 2){         input_filename = argv[1];    }       yyin = fopen(input_filename, "r");    if (!yyin){        perror("failed to open file\n");        return -1;     }       yylex();    fclose(yyin);    return 0;}

编译:

flex -o c1 flex1gcc -o exe1 c1flex -o c2 flex2gcc -o exe2 c2

测试:

./exe1 input > tmp./exe2 tmp > output

output中的代码以及没有了注释和多余空行。

0 0