把C/C++程序代码中的注释去掉,并返回结果
2013-01-20 11:58
567 查看
#include <stdio.h> #include <string.h> #include <fcntl.h> void remove_commit(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("/home/lyd/Hello.c", O_RDONLY, 0); if (fd == -1) { return -1; } n = read(fd, buf, sizeof(buf)); if (n == -1 || n == 0) { close(fd); return -1; } remove_commit(buf, n); *(buf + n) = '\0'; printf(buf); close(fd); return 0; }
相关文章推荐
- 编写一个函数,实现把C/C++程序代码中的注释去掉,并把结果返回。
- 去掉C/C++程序代码中的注释
- 去掉C/C++程序代码中的注释
- 编写程序将C / C++代码中的注释去掉
- 【c++程序】代码注释标准
- 【编写高质量代码:改善C++程序的150个建议 之 0.0】 不要让你的Main函数返回void
- C++格式化代码,去掉vs2010编辑器里中文注释的红色波浪线
- 我的程序(4):C++代码注释分离
- 去掉C/C++程序中的注释
- 去除C/C++程序代码中的注释
- 写一个函数,可以处理C++代码,将其中的注释去掉
- 最基本的C++ 窗口程序代码及完整注释
- 《程序员面试宝典》移除C/C++程序代码中的注释
- c#调用Oracle存储过程返回的游标结果代码实例
- android按2次返回键退出程序的代码
- 编一个程序,从 string 对象中去掉标点符号。要求输入到程序的字符串必须含有标点符号,输出结果则是去掉标点符号后的 string 对象。
- 计算java文件有多少行注释行,正常代码行,空白行的程序,swing做的
- C++文本查询程序 不要定义类和智能指针管理数据 C++Primer练习12.28 使用vector,map,set容器保存来自文件的数据并生成查询结果
- 2014秋C++ 第15周项目2程序阅读(加注释)
- 编写高质量代码改善C#程序的157个建议——建议26:使用匿名类型存储LINQ查询结果