您的位置:首页 > 编程语言 > C语言/C++

《程序员面试宝典》移除C/C++程序代码中的注释

2013-11-16 00:09 381 查看
最近在看《程序员面试宝典》,受益匪浅,这篇文章是5.8节的代码,加了我的注释,还规范了代码,共享之。 (*^__^*) ……

#include <string.h>

#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,//扫描指针

c, //暂存扫描字符

*end; //指向文末

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 (NULL == sq_start)

{

sq_start = p;

p++;

}

else

{

len = p++ - sq_start;

if (2 == len && '\\' == *(sq_start+1))

{

//忽略字符中的单引号

continue;

}

sq_start = NULL;

}

break;

case '\"': //遇到双引号(")

if (sq_start || lc_start || bc_start)

{

//忽略字符与注释中的单引号

p++;

continue;

}

if (NULL == dq_start)

{

dq_start = p;

p++;

}

else

{

len = p++ - dq_start;

if ('\\' == *(p-2))

{

//忽略字符串中的双引号

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 || NULL == bc_start)

{

//忽略字符、字符串与行注释中的星号,还有忽略乘号

p++;

continue;

}

if ('/' != *(p+1))

{

//忽略块注释中的星号

p++;

continue;

}

len = (p+1) - bc_start + 1;

memset(bc_start, ' ', len);

p += 2;

bc_start = NULL;

break;

case '\n': //遇到换行符

if (NULL == lc_start)

{

//不是行注释的换行符则忽略

p++;

continue;

}

c = *(p-1);

len = ('\r'==c ? p-1 : p) - lc_start;

memset(lc_start, ' ', len);

p++;

lc_start = NULL;

break;

default:

p++;

break;

}

}

//如果最后一行是行注释

if (lc_start)

{

len = p - lc_start;

memset(lc_start, ' ', len);

}

}

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

{

int fd, n;

char buf[102400];

fd = open("C:\\uuu.txt", O_RDONLY, 0);

if (-1 == fd)

{

return -1;

}

n = read(fd, buf, sizeof(buf));

if (-1==n || 0==n)

{

close(fd);

return -1;

}

remove_comment(buf, n);

*(buf+n) = '\0';

printf(buf);

close(fd);

return 0;

}

直接用这代码测试,结果截图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: