剔出//与/**/注释的源码

//main.c

#include <stdio.h>
#include <ctype.h>

#define MAXLINE 1024
#define SKIPSPACE(p) while(isspace(*p)) p++;

FILE *yyin=NULL;
char srcbuf[MAXLINE<<1];
int lineno=0;   //当前行

static void ShowHelp(void);
static void ShowError(char *msg);
static void ShowWarning(char *msg);
static char* SkipComment(char* p);
static void GetNextLine(void);

int main(int argc, char *argv[], char *envp[])
{
    if(argc<2) {
        ShowHelp();
        return 0;
    }

    if((yyin=fopen(argv[1],"r"))==NULL) {
        ShowError("File Not Found!");
        return 0;
    }

    while(!feof(yyin)) {
        GetNextLine();
        printf("%4d: %s/n", lineno, srcbuf);
    }

    fclose(yyin);

    return 0;
}
static void ShowHelp(void)
{
    printf("语法:RemoveComment [file]/n");
}

static void ShowError(char *msg)
{
    printf("Error: %s/n", msg);
    //exit(1);
}

static void ShowWarning(char *msg)
{
    printf("Warning: %s/n", msg);
}

static char* SkipComment(char* p)
{
    p++;

    while(1) {
        while((*p!='/n')&&(*p!=0)) {
            if(*p++=='*') {
                if(*p++=='/') {
                    //if(*p<=32) {
                    //    printf("Debug In SkipComment: %d./n", *p);
                    //} else {
                    //    printf("Debug In SkipComment: Char Of %c./n", *p);
                    //}
                    return p;
                }
            }
        }
        //重些获取一个新行
        p=srcbuf+MAXLINE;
        if(fgets(p, MAXLINE, yyin)) {
            lineno++;
        } else {
            ShowError("源文件在/* */注释中结束!");
            break;
        }
    }

    return NULL;
}

static void GetNextLine(void)
{
    register char *p, *tmp;
    char c;

    p=tmp=srcbuf;
    *p=0;

    if(yyin==NULL) return;
    //if(feof(yyin)) return;

    if(fgets(p,MAXLINE,yyin)!=NULL) {
        lineno++;
        //SKIPSPACE(tmp);
        while(((c=*tmp++)!='/n')&&(c!=0)) {
            if(c=='/') {
                if(*tmp=='/') break;       // //形式的注释,本行处理结束
                if(*tmp=='*') {            //如果为 /**/形式的注释
                    if((tmp=SkipComment(tmp))==NULL) {
                        break;
                    }
                    continue;
                }
            }
            *p++=c;
        }
        *p=0;
    }
 
}

实现:

1、剔出//与/* */注释

2、加行号

收获:

1、所有系统带.h文件用<>进行#include

2、读取缓冲区为至少两个MAXLINE大小,是因为跳过/**/的处理需要临时缓冲区的缘故

参考资料:

1、MUDOS v22.2b14源码

2、《C语言的科学和艺术》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值