使用两个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 flex1
gcc -o exe1 c1
flex -o c2 flex2
gcc -o exe2 c2
测试:
./exe1 input > tmp
./exe2 tmp > output
output中的代码以及没有了注释和多余空行。
|