当代码写完的时候。有时候我们想要删除其中的注释,如果在源文件中一个一个地找,那么会耗费大量的时间。于是我写了一个方法自动读取cpp文件并且找到其中的注释的语句,把它删除。下面是我的函数。
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#define NULLCHAR 32 //ascii字符的32表示空字符
void delComments(const char *path);
int main(int argc, const char * argv[])
{
delComments("/Users/zctech/Desktop/1.cpp");
return 0;
}
//删除注释.path:文件名
void delComments(const char *path)
{
int fd = open(path, O_RDWR);
//获取文件大小
struct stat sb;
fstat(fd, &sb);
unsigned char *start = (unsigned char *)mmap(NULL, sb.st_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if(start == MAP_FAILED) /* 判断是否映射成功 */
{
printf("映射失败,文件过大或者没有权限");
return;
}
printf("%s", start);
//判断是否为 【/**/】 型注释, 注意当是字符串的时候不替换
unsigned long i = 0;
bool isCom = false;
bool isStr = false;
while (i < sb.st_size)
{
if(!isStr && '/' == *(start + i) && '*' == *(start + i + 1))
{
isCom = true;
}
else if(!isStr && '*' == *(start + i) && '/' == *(start + i + 1))
{
isCom = false;
*(start + i) = *(start + i + 1) = NULLCHAR;
}
else if(!isCom && !isStr && '\"' == *(start + i))
{
isStr = true;
}
else if(!isCom && isStr && '\"' == *(start + i))
{
isStr = false;
}
//移除注释
if (isCom && !isStr)
{
*(start + i) = NULLCHAR;
}
i++;
}
//判断是否为【//】 型注释, 注意当是字符串的时候不替换
i = 0;
isCom = false;
isStr = false;
while (i < sb.st_size)
{
if(!isStr && '/' == *(start + i) && '/' == *(start + i + 1))
{
isCom = true;
}
else if(!isStr && '\n' == *(start + i))
{
isCom = false;
}
else if(!isCom