程序员面试宝典学习笔记——删除C/C++代码中的注释

#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <io.h>
#include <fcntl.h>
#include <stdlib.h>
using namespace std;

//功能:删除C/C++代码中的注释
//输入:指向C/C++程序代码的指针

void remove_commment(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);
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 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_commment(buf,n);
*(buf+n)='\0';
printf(buf);
close(fd);
return 0;
 }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值