用lex处理C语言的注释

最近在实践中遇到一个需求:需要把一个C语言代码文件中的注释中的非空白字符全部替换为空格(目的是让新文件的行数和原来的一样,以便调试)..用flex鼓捣了两个小时,得到了下面的代码

%{	
#include<iostream>
#include<sstream>
#include<fstream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
ostringstream oss;
%}
 
%start LINE_COMMENT BLOCK_COMMENT STRING
 
%%
 
%{
// 处理字符串常量,lex的注释必须写在%{和%}之内!!
%}

<STRING,INITIAL,BLOCK_COMMENT>[ \t\n] { oss<<yytext; }
<INITIAL>\"	{ oss << yytext; BEGIN STRING;}
<STRING>[^\\]\"	{ oss << yytext; BEGIN 0; }


<INITIAL>"//"  {oss << "  "; BEGIN LINE_COMMENT;}
<LINE_COMMENT>\n {	oss<<endl; BEGIN 0; }
<LINE_COMMENT>. {oss << " ";}

<INITIAL>"/*"  {oss << " ";BEGIN BLOCK_COMMENT;}
<BLOCK_COMMENT>"*/"  {oss << " ";BEGIN 0;}
<BLOCK_COMMENT>. {	oss<<" ";	}

<STRING,INITIAL>. { oss<<yytext; }
 
%%
int yywrap(void)
{  
	return 1;  
}
 
int main(int argc, char* argv[])
{
	//cout <<"hello world" <<endl;
	char* infilename = NULL;
	char* outfilename = NULL;
	
    if(argc > 1){
    	infilename = argv[1];
    	outfilename = argv[1];
	}
	
	if(argc > 2){
    	outfilename = argv[2];
	}
	
	if (infilename)
		yyin=fopen(infilename,"r");
    else{
        yyin = stdin;
	}
	
    yylex();
    
    
    
    if (infilename){
    	fclose(yyin);
    }
    
    const string & str = oss.str();
    
    //将字符串流中的数据复制到输出流中
    if (outfilename){
    	ofstream ofs(outfilename);
		copy(str.begin(),str.end(),ostream_iterator<char>(ofs));    
    }
    else {
    	copy(str.begin(),str.end(),ostream_iterator<char>(cout));
    }
    
    return 0;
}

测试文件内容为:

//行注释测试
int main(){
	const char* p ="//字符串里的注释" ;
	/*
	块注释
	*/
	return  0;
}

运行后文件的新内容为

           
int main(){
	const char* p ="//字符串里的注释" ;
	 
	      
	 
	return  0;
}

运行成功.

 

linux下的实验过程为:

sudo apt-get install flex  #安装flex包
sudo apt-get install bison #按照bison
flex demo.l      #编译刚才写的demo.l文件,会自动生成一个lex.yy.c文件
g++ -Wall -Wextra -o remove_comment lex.yy.c # 编译之
./remove_comment test1.c    #消除test1.c中的所有注释

 

vs中如何使用flex 可以见这篇文章:

vs2017下使用flex+bison

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值