c语言自动删除cpp文件中的注释 使用代码删除注释【Linux、mac下】

介绍了一种方法,通过编写代码自动读取并删除cpp文件中的注释,节省手动删除的时间。提供了示例代码展示如何删除单个文件及整个文件夹下cpp文件的注释,特别提到可通过修改函数来处理#pragma等特殊注释。
摘要由CSDN通过智能技术生成

当代码写完的时候。有时候我们想要删除其中的注释,如果在源文件中一个一个地找,那么会耗费大量的时间。于是我写了一个方法自动读取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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值