C++去掉註釋

#include
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>


/*****
 *功能:移除C/C++程序代碼中的註釋
 *
 *輸入:指向C/C++程序代碼的指針


 */


void remove_comment(char *buf,size_t size)
{
char *p,*end,c;
//單引號,雙引號,單行註釋,多行註釋
char *sq_start,*dq_start;
char *lc_start,*bc_start;
size_t len;


p=buf;
end = p+size;
sq_start= NULL;
dq_start=NULL;


lc_start=NULL;
bc_start=NULL;


while (p<end)
{
c=*p;
switch(c)
{
case '\'':
if (dq_start || lc_start || bc_start)
{


//忽略字符串與註釋中的單引號
p++;
continue;
}
if(sq_start == NULL)
{


sq_start = p++;
}
else 
{
len==p++- sq_start;
}
if (len == 2 && *(sq_start+1)== '\\')
{


//忽略字符串中的單引號
continue;
}


sq_start =NULL;
break;
case '\"':   //雙引號
if (sq_start || lc_start || bc_start)
{
//忽略字符或註釋中的雙引號
p++;
continue;
}


if (dq_start ==NULL)
{
dq_start = p++;
}
else
{


if (*(p++ -1)== '\\')
{


//忽略字符串中的雙引號
continue;
}
dq_start = NULL;
}
break;


case '/':
if (sq_start || dq_start ||lc_start ||bc_start)
{


//忽略字符,字符串或註釋中的斜槓
p++;
continue;


}
c = *(p+1);

if (c=='/')
{
lc_start = p;
p+=2;


}
else if (c=='*') 
{
bc_start = p;
p += 2;
}
else
{


//忽略除號
p++;
}
break;


case '*':
if (sq_start || dq_start || lc_start ||bc_start ==NULL)
{
//忽略字符、字符串或行註釋中的星號,還有忽略乘號
p++;
continue;
}


if ( *(p+1) != '/')
{
//忽略塊註釋中的星號
p++;
continue;
}
p+=2;
memset(bc_start,' ',p-bc_start);
bc_start =NULL;
break;


case '\n':
if (lc_start ==NULL)
{
p++;
continue;
}


c=*(p+1);
memset(lc_start,' ',(c == '\r'?(p++ -1) : p++)-lc_start);
lc_start = NULL;


break;
default:
p++;
break;
}
}

if (lc_start)
{
memset(lc_start,' ',p-lc_start);
}


}




int main(int argc ,char * argv[])
{


int fd,n;
char buf[102400];
fd = open("C:\\uuu.txt",_O_RDONLY,0);
if (fd==-1)
{
return -1;
}


n = read(fd,buf,sizeof(buf));
if (n==-1 || n==0)
{
close(fd);
return -1;
}


remove_comment(buf,n);
*(buf+n) = '\0';
printf(buf);


close(fd);
return 0;


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章